Count


#1

this is my code:

def count(sequence, item):
  total = 0
  List = 0
  for things in sequence:
    List += 1
    if sequence[List] == item:
      total += 1
      return total
    else:
      return 0

it gives an index out of range error for [1], 7, can someone explain why?


#2

you increase List before doing sequence[List], this will cause an index error

for [1] you increase the index from 0 to 1, and then attempt to use 1 to access the list (index error)

i don’t see why you have List at all. the loop will assign each value in the list (in order) to the loop iterator things, so you can just check if things equals item

proof of concept:

example = ['a','b','c']
for letter in example:
    print letter

see? access the the list item without counter (List)


#3

thanks for your help, I thought i needed List to have a number for the sequence[List] line, but i just used things instead


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.