1

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 1

6

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]
Sign up to request clarification or add additional context in comments.

3 Comments

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]?
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].
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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.