In short, I am making a function that takes 2 arguments 'sequence' and 'item'. The 'sequence' can be anything - an integer, a string, or a list containing integers or strings. I am trying to make a function that counts the amount of times 'item' occurs in the 'sequence'. Please take into account, I am still a newbie at Python. A simple answer would be very much appreciated. This is what I have so far
def count(sequence, item):
found = 0
if sequence == item:
found += 1
return found
else:
for num in sequence:
if num == sequence:
found += 1
return found
else:
return False
print count([4,'foo',5,'hi'], 5)
The else
part of the code is meant to be enabled if the sequence
is something like a list. I was thinking I should loop through the list using for
and do the same thing - but it's not working as it keeps returning False
which follows the second 'else' statement. Any idea how I can do this? For clarification, the output in the example above should be 1
because '5' occurs once in the list.