Back

Explore Courses Blog Tutorials Interview Questions

Explore Tech Questions and Answers

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

+2 votes
3 views
by (10.2k points)
I have an item and I want to count it's occurrence in a list, How can I do that in Python?

3 Answers

0 votes
by (46k points)
edited by

You can use count method :

>>> from collections import Counter
>>> a = ['violet', 'Indigo', 'violet', 'green', 'violet', 'indigo', 'violet' , ' green' , 'Indigo']

>>> Counter(z)
Counter({'violet': 4, 'Indigo': 2, 'green': 1})

Hope this helps, Cheers....!! 

0 votes
by (20.3k points)

If you are working on Python 2.7 or 3 and you want the number of occurrences for each element then try this:

>>> from collections import Counter

>>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']

>>> Counter(z)

Counter({'blue': 3, 'red': 2, 'yellow': 1})

0 votes
by (106k points)

If you only want one item's count, use the count method:

>>> [1, 2, 3, 4, 1, 4, 1].count(1) 

3

Related questions

+3 votes
2 answers
+1 vote
2 answers
0 votes
2 answers
asked May 30, 2019 in Python by Anvi (10.2k points)
+3 votes
2 answers

Browse Categories

...