Python List method. count()

Hi team,

Just a quick question. Let’s say we have a list like this:

food = [(1, 'cheese'), (2, 'mushrooms'), (2, 'mushrooms'), (2, 'pepperoni'), (3, 'sausage'), (6, 'pineapple'), (7, 'anchovies')]

How to find the number of (2, ‘mushrooms’) in this list?
As far as I know, the count() method only takes one argument. Therefore, I need to know if there is another way that we can count the element in question?

Thanks,
Jimmy

Hello @jimmywijaya. You could loop through the first list, and return the count of the iterating variable:

a = [[9, 8], [9, 8]]
for i in a: #declares the iterating variable-each of the sub-lists in a
 print(i.count(9))#prints the count of the number of 9s in each of
#the sub-lists in a

this therefore prints:

1
1

I hope this helps!

1 Like

@jimmywijaya
You can count the tuple by passing is to the count method as one argument.

food.count((2, 'mushrooms'))

That should work.

Hi regan,

Thank you, I will give this a try.

Cheers,
Jimmy