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
18,223 views

8 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
thank you so much. you saved my day. i was really stuck at finding this answer.
+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
0 votes

Hi, @Everyone,

There are a few functions that can be used to get the frequency of occurrence in a string. So, how do you count frequency in Python?

using list(): Split the string into a list containing the words by using a split function (i.e. string.split()) in python with delimiter space.

using set(): Split the string into a list containing the words by using a split function (i.e. string.split()) in python with delimiter space.
 Use set() method to remove a duplicate and to give a set of unique words

Using a Dictionary

answered Jul 8, 2020 by Gitika
• 65,870 points
0 votes

Here is one of the ways to get the number of occurrences when you working with array in python. So, I am sharing one example on how do you count the frequency of an element in an array in Python? 

 Loop through the array and count the occurrence of each element as frequency and store it in another array fr:

1    2   8  3   2   2   2   5   1  

arr = [1, 2, 8, 3, 2, 2, 2, 5, 1];     

#Array fr will store frequencies of element    

fr = [None] * len(arr);    

visited = -1;    

for i in range(0, len(arr)):    

    count = 1;    

    for j in range(i+1, len(arr)):    

        if(arr[i] == arr[j]):    

            count = count + 1;    

            #To avoid counting same element again    

            fr[j] = visited;    

                  if(fr[i] != visited):    

               fr[i] = count;    

     #Displays the frequency of each element present in array    

print("---------------------");    

print(" Element | Frequency");    

print("---------------------");    

for i in range(0, len(fr)):    

    if(fr[i] != visited):    

        print("    " + str(arr[i]) + "    |    " + str(fr[i]));    

print("---------------------");  
answered Jul 8, 2020 by Aditi
0 votes

Using a dictionary

Here we capture the items as the keys of a dictionary and their frequencies as the values.

list = ['a','b','a','c','d','c','c']
frequency = {}
for item in list:
   if (item in frequency):
      frequency[item] += 1
   else:
      frequency[item] = 1
for key, value in frequency.items():
   print("% s -> % d" % (key, value))

Running the above code gives us the following result −

a -> 2
b -> 1
c -> 3
d -> 1

answered Jul 12, 2020 by Swati
0 votes

Given an unsorted list of some elements(may or may not be integers), Find the frequency of each distinct element in the list using a dictionary.

Example:

Input : [1, 1, 1, 5, 5, 3, 1, 3, 3, 1,
                  4, 4, 4, 2, 2, 2, 2]
Output : 1 : 5
         2 : 4
         3 : 3
         4 : 3
         5 : 2
Explanation : Here 1 occurs 5 times, 2 
              occurs 4 times and so on...

# Python program to count the frequency of 

# elements in a list using a dictionary

  

def CountFrequency(my_list):

  

    # Creating an empty dictionary 

    freq = {}

    for item in my_list:

        if (item in freq):

            freq[item] += 1

        else:

            freq[item] = 1

  

    for key, value in freq.items():

        print ("% d : % d"%(key, value))

  

# Driver function

if __name__ == "__main__": 

    my_list =[1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2]

  

    CountFrequency(my_list)

Output:

 1 :  5
 2 :  4
 3 :  3
 4 :  3
 5 :  2

Time Complexity:O(N), where N is the length of the list.

answered Dec 16, 2020 by Roshni
• 10,420 points

Related Questions In Python

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
355 views
0 votes
1 answer

How to find the index of an item in a list?

One thing that is really helpful in ...READ MORE

answered Dec 3, 2020 in Python by Gitika
• 65,870 points
118 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, 2019 in Python by Mohammad
• 3,210 points
294 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 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 1,842 views
0 votes
0 answers
+4 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,810 points
1,419 views
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
151 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
136 views