count() Method for Lists in Python (2 Examples)


In this Python tutorial, you’ll learn how to apply the count() method to Python lists to return the frequency of the elements in this list.

The article contains the following content:

Let’s go straight to the examples.


Exemplifying Data

We will be using the following data as an example for this tutorial.

my_list = ['blue', 'green', 'red', 'blue', 'purple', 'yellow']

As shown in the Python output, we have constructed a list object that contains 6 strings under the name my_list.

Let’s see how the count() method works using my_list in the following examples.


Example 1: Apply count() Method to Obtain Frequency of Certain Element in List

This example illustrates the basic use of the count() method, which is extracting the number of occurrences of a particular element in a list. For demonstration, we will return the count of string “blue” in my_list.

# 2

As the previous output shows, our list contains the character string “blue” twice.


Example 2: Apply count() Method to Obtain Frequency of Each Element in List

Imagine that we want to get the number of occurrences for each element in the list. In such a case, we can use the count() method inside a list comprehension to iterate through our list. Take a look at the following code.

new_list = [[l, my_list.count(l)] for l in set(my_list)]
# [['blue', 2], ['purple', 1], ['green', 1], ['yellow', 1], ['red', 1]]

The output shows the new list that contains the lists of strings and their counts (i.e., 1 for green and so on) in my_list.

We can also create a dictionary using the dict() function.

dictionary = dict((l, my_list.count(l)) for l in set(my_list))
# {'blue': 2, 'purple': 1, 'green': 1, 'yellow': 1, 'red': 1}

The printed counts are the same as shown in the previous output, yet they are now stored in a dictionary instead of a list.


Video, Further Resources & Summary

Do you need more explanations on how to use the count() function in Python? Then you should look at the following YouTube video of the Statistics Globe YouTube channel.


The YouTube video will be added soon.


Furthermore, you could have a look at the related tutorials on this website:

This post has shown how to apply the count() method for lists in Python. Let us know if you have additional questions in the comments section below.


Paula Villasante Soriano Statistician & R Programmer

This page was created in collaboration with Paula Villasante Soriano. Please have a look at Paula’s author page to get more information about her academic background and the other articles she has written for Statistics Globe.


Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.

Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.