Python Practice Makes Perfect 11/15 Count


#1
def count(sequence, item):
  count = 0
  for sth in sequence:
    if sth == item:
      count += 1
  return count

Actually it says this is right and working, but am i thinking too much for this example?

of course it counts right when variable ‘sequence’ is a normal list like [1,2,3,1]

but it doesn’t count right when the list has a list in it, like [1,2,[1,2,3]]

Am I thinking out of bounds? Didn’t example want to think that much?

Whether or not, how can i count an item in the list in another list?


#2

its a nice bonus challenge

the simplest solution would be to check if type of sth is a list, of so, use another loop to loop over sth and increase count when needed


#3

def count(sequence, item):
count = 0
for sth in sequence:
if type(sth) is list:
for i in sth:
if i == item:
count += 1
elif sth == item:
count += 1
return count

Thanks for reply! I tried this and it worked well.


#4

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