How can I count how many times 3 appears in a list of list such as [[1,2,3,4],[2,3,4,5],[5,6,7,5]]
the output should be something like [1,1,0]
1 Answer
You can use the method list.count(element):
my_lists = [[1,2,3,4], [2,3,4,5], [5,6,7,5]]
[l.count(3) for l in my_lists]
>> [1, 1, 0]
3 Comments
user1813564
Pretty useful!then how abt words?such as check how many times apple appears in a list['applepie','applesmoothies','banana'] and return [1,1,0]?
Nicolas
In this example, there is a loop on each element of
my_lists and for each element l (a sublist), we count the number of times "3" appears in this list. The list comprehension allows us to append each time the number of occurences to the resulting list, so as to get [1, 1, 0].Nicolas
If you want to know the number of times the string
apple appears in the elements of the list ['applepie', 'applesmoothies', 'banana'], you can't use my_list.count('apple') because the search is exact. You will have to use something like sum(1 for s in my_list if 'apple' in s).