Count the frequency of an item in a python list

+1 vote
Is there a function in Python that counts the number of occurrences of an item in Python?
Apr 16, 2018 in Python by NEET
90 views

4 answers to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
+1 vote

I think the function you are looking for is count():

>>> [1,1,2,3,5,6,8,6,3,2,4].count(3)
2
answered Apr 16, 2018 by Nietzsche's daemon
• 4,260 points
+1 vote
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
from itertools import groupby
[len(list(group)) for key, group in groupby(a)]

Output:

[4, 4, 2, 1, 2]
answered Oct 18, 2018 by nabarupa
+1 vote
import collections
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
counter=collections.Counter(a)
print(counter)
# Counter({1: 4, 2: 4, 3: 2, 5: 2, 4: 1})
print(counter.values())
# [4, 4, 2, 1, 2]
print(counter.keys())
# [1, 2, 3, 4, 5]
print(counter.most_common(3))
# [(1, 4), (2, 4), (3, 2)]

If you are using Python 2.6 or older, you can download it here.

answered Oct 18, 2018 by Esha
+1 vote

To count the number of appearances:

from collections import defaultdict

appearances = defaultdict(int)

for curr in a:
    appearances[curr] += 1

To remove duplicates:

a = set(a) 
answered Oct 18, 2018 by tinitales

Related Questions In Python

0 votes
1 answer

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

len() >>> mylist=[] >>> print len(mylist) 0 READ MORE

answered Dec 12, 2018 in Python by charlie_brown
• 7,710 points
42 views
0 votes
1 answer

how do I check the length of an array in a python program?

lets say we have a list mylist = ...READ MORE

answered Mar 12 in Python by Mohammad
• 1,400 points
16 views
0 votes
1 answer

How to count the number of elements in a list?

To count the number of elements of ...READ MORE

answered May 27 in Python by Nisa
• 640 points
6 views
0 votes
1 answer

how can i count the items in a list?

suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE

answered May 2 in Python by Mohammad
• 1,400 points
54 views
+4 votes
6 answers
0 votes
1 answer

Count the frequency of all list items

You can do this using a dictionary: dict((i, ...READ MORE

answered May 3, 2018 in Python by Nietzsche's daemon
• 4,260 points
15 views
0 votes
1 answer

Sorting a list of strings in Python

Use the sort function mylist.sort() READ MORE

answered May 29, 2018 in Python by Nietzsche's daemon
• 4,260 points
15 views

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.