# Can you count the number of occurrences using .count() on a list of lists?

On this python project we are asked to combine two individual lists ‘toppings’ and ‘cost’ into a list of lists called ‘pizzas’. Then part of this problem is asking to use the function .count() on the single list ‘cost’ to count the number of times the number 2 is on such list. However, I was wondering if there was a way or another function similar to .count() that would let me count an occurrence from a list of lists.

single lists where i can use the function .count()
toppings = [ ‘pepperoni’, ‘pineapple’, ‘cheese’, ‘sausage’, ‘olives’, ‘anchovies’, ‘mushroom’]
cost = [2, 6, 1, 3, 2, 7, 2]

List of lists where the fuction .count() doesn’t work.
pizzas = [(1, ‘cheese’), (2, ‘mushroom’), (2, ‘olives’), (2, ‘pepperoni’), (3, ‘sausage’), (6, ‘pineapple’), (7, ‘anchovies’)]

Thanks,

i googled, and got the following stackoverflow question:

https://stackoverflow.com/questions/5828123/nested-list-and-count

if you only have nested lists within the out list, this seems a very good idea:

`````` L = [[1, 2, 3], [1, 1, 1]]
sum(x.count(1) for x in L)
``````

remember, SO and google are you friend

1 Like

If list.count counts a particular item in a list, but you don’t have a list of such items, then get such a list first, right?

So how would you go from
`(1, 'cheese')`
to
`'cheese'`
?
Do that on each thing in the list, then you can count.

Changing the shape of your data to fit your operation is often the right thing to do, it’s better than having an operations that bend over backwards to fit the data.