How can I count the occurrences of a list item

0 votes
Given an item, how to count its occurrences in a list in Python?
Feb 5, 2022 in Python by Dev
• 6,000 points
566 views

1 answer to this question.

0 votes

For Counting the occurrences there are many ways

1) Using count() 

For Example:
Categories = [12,34,45,56,67,12,12,34,45,56,56,45,56]
Categories.count(12)

Output

3

2) Counting all occurrences witjh count() method and using it either with or without dictionary

[[x,Categories.count(x)] for x in set(Categories)]  

Output:

[[34, 2], [67, 1], [12, 3], [45, 3], [56, 4]]
dict((x,Categories.count(x)) for x in set(Categories))

Output:

{34: 2, 67: 1, 12: 3, 45: 3, 56: 4}

The Output will be the same but the way it is been displayed is different.

3) Using Counter form collections library
from collections import Counter
Counter(Categories)

Output:

Counter({12: 3, 34: 2, 45: 3, 56: 4, 67: 1})

Hope this helps.

answered Feb 7, 2022 by Nandini
• 5,480 points

Related Questions In Python

0 votes
1 answer

How can I count the occurrences of a list item?

If you only want one item's count, ...READ MORE

answered Dec 18, 2020 in Python by Gitika
• 65,770 points
658 views
0 votes
2 answers

How can I get the count of a list in Python?

n=[1,2,3,4,5,6,7,8,9] print(len(n)) =9 READ MORE

answered Dec 10, 2020 in Python by anonymous
1,485 views
+2 votes
2 answers

In a list of dictionaries, how can I find the minimum calue in a common dictionary field.

There are several options. Here is a ...READ MORE

answered Apr 10, 2018 in Python by charlie_brown
• 7,720 points
1,413 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,434 views
0 votes
1 answer
0 votes
1 answer

How can I get list of values from dict?

Here is an example to get the ...READ MORE

answered Feb 14, 2022 in Python by Nandini
• 5,480 points
1,236 views
0 votes
1 answer

How can I add new keys to a dictionary in Python?

Yes, it is possible to add new ...READ MORE

answered Feb 9, 2022 in Python by Nandini
• 5,480 points
555 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP