How to Count Occurrences of an Element in a list in Python

This tutorial is about How To Count Occurrences Of An Element In A List In Python. Lists can contain even duplicate values. Like arrays, lists are the collection of ordered items. The main difference is that arrays consist of items with the same datatype whereas lists can consist of items with different datatypes.

If you want to learn more about lists in Python, See Python List Tutorials or Python Tutorials.

For instance, Given a list x= [1,2,2,7,4,7,2,9,1,4,3] in which 1, 2, 7, 4, 9, 3 appears 2, 3, 2, 2, 1, 1 times respectively. In python, counting occurrences of an element in the list. There are various ways to count multiple occurrences of the same element in the list. Let’s discuss them.

methods to count occurences

  • Method 1: Counting Occurrences using builtin count() function.
  • Method 2: Using loops to count unique values and elements in the list.
  • Method 3: Using Counter class.

Using built-in count() function to count occurrences in a list

The python has a built-in count() function which takes a value as an argument whose count you want to find in the list. It will return an integer value that represents the number of times a specified item occurs in the list. If the integer does not exist, it returns 0.

Example 1:

# Create a list of integers

list1 = [1, 2, 2, 7, 2, 9, 1, 4, 3]

x = list1.count(2)

print("The number 2 occurs " + str(x) + " times in the list.")

Output: 

The number 2 occurs 3 times in the list.
  

Example 2:

Similarly, if you apply the same method to determine the same elements in strings.

# Create a list of Strings

list1 = ['mango', 'mango', 'guava', 'apple', 'guava', 'mango', 'apple']

x = list1.count('apple')

print("The Fruit 'apple' occurs " + str(x) + " times in the list.")

x = list1.count('orange')

print("The Fruit 'orange' occurs " + str(x) + " times in the list.")
  
output of program to count occurrences in list of python using built in function count()

using loop to count occurrences

One other method to count occurrences in the list is using a loop. First of all, initialize a list and declare a variable to store the count of a specified element. Then iterate over the list using for loop and if the specified element exists, increment the variable by 1. Let’s see how it works through an example.

Example 3:

# Program to count number of occurences of a specified element in a list

def counter(list1, x):
   count = 0
   for item in list1;
            if (item == x):
                 count = count + 1
    return count

# Creating an empty list

list1 =[]

n = int(input("Enter number of elements : "))

for i in range(n)
            item = int(input())
            # Add the item in the list
            list1.append(item)

x = int(input("Enter the number whose count you want to find in the list: "))

y = counter(list1,x)

print('The element %s appears %s times in the list'%(x,y))
 

Output:

output for same values in list using loops python

using counter class to determine unique values in list

The above two methods are useful when you want to find the count of any item in the list. The third method is to use a counter class from the collections module. Counter returns a dictionary consisting of all elements and their occurrences as a key-value pair, where the key is the item and value represents the number of times that item has occurred in the list. This method not only provides the count of a single item but can also provide the count of all items from the list.  

Example:

Suppose you have a list of student grades and you want to find how many of them have got A, B, C, D, and F grades.

code for same values for list

Output:

output for counting occurrences in list

The last line on the output screen shows each item along with its frequency. You can also extract keys and their values in separate lists as shown in the code snippet below.

another code for counting same elements in list using counter class

Output:

If you observe the output screen, you’ll see that the keys contain all the unique elements found in the list1. The length of keys gives the total number of unique values in the list1.

There are numerous applications in which you have lists consisting of a huge amount of data and to find the occurrence of any single item or all items, you can use the above-mentioned methods to obtain the frequency of items. If you find any confusion regarding anything in the article, let us know in the comments. Your feedback matters a lot to us.

Leave a Comment

Your email address will not be published. Required fields are marked *