pythonlist

count the elements in a list


The problem is to count the elements in a list without using len(list).

My code:

def countFruits(crops):
  count = 0
  for fruit in crops:
    count = count + fruit
  return count

The error was: 'int' and 'str'

These are supposed to be the test cases that should run the program.

crops = ['apple', 'apple', 'orange', 'strawberry', 'banana','strawberry', 'apple']
count = countFruits(crops)
print count
7

Solution

  • Try this:

    def countFruits(crops):
      count = 0
      for fruit in crops:
        count = count + 1
      return count
    

    To calculate the length of the list you simply have to add 1 to the counter for each element found, ignoring the fruit. Alternatively, you can write the line with the addition like this:

    count += 1
    

    And because we're not actually using the fruit, we can write the for like this:

    for _ in crops:
    

    Making both modifications, here's the final version of the implementation:

    def countFruits(crops):
        count = 0
        for _ in crops:
            count += 1
        return count