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
1,555 views

4 answers to this question.

+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,720 points
95 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
• 3,060 points
59 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
• 1,090 points
28 views
+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 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 346 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
34 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
45 views