Count Duplicates in List in Python (2 Examples)
In this Python tutorial you’ll learn how to count the number of repeated items in a list.
The page will contain the following contents:
Let’s dive right into the examples.
Creation of Exemplifying Data
The data below is used as a basis for this Python programming tutorial:
my_list = ['a', 'c', 'b', 'a', 'a', 'c'] # Create example list print(my_list) # Print example list # ['a', 'c', 'b', 'a', 'a', 'c']
Have a look at the previous output of the Python console. It shows that our example data is a list object containing six list elements.
Some of these elements appear several times. Let’s count how often each value occurrs!
Example 1: Count Repeated Elements in List Using count() Function
In this example, I’ll show how to use the count method to return the number of occurrences of each list element.
Consider the Python code below. We iterate over the elements in our list to get the different counts:
my_list_count1 = {i:my_list.count(i) for i in my_list} # Apply count function print(my_list_count1) # Print list counts # {'a': 3, 'c': 2, 'b': 1}
As shown in the output above, the character ‘a’ appears three times in our list, the character ‘c’ appears twice, and the character ‘a’ is unique.
Example 2: Count Repeated Elements in List Using Counter() Function of collections Module
Alternatively to the count method (demonstrated in Example 1), we can also use the Counter function of the collections module.
First, we have to import Counter from the collections module:
from collections import Counter # Import Counter
Next, we can apply the Counter function to our list object to get the number of times every value occurrs:
my_list_count2 = Counter(my_list) # Apply Counter function print(my_list_count2) # Print list counts # Counter({'a': 3, 'c': 2, 'b': 1})
The printed counts above are the same as in Example 1. However, this time we have employed the Counter function of the collections module instead of the count method.
Video, Further Resources & Summary
Have a look at the following video on my YouTube channel. I demonstrate the Python programming code of this tutorial in the video tutorial:
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
Furthermore, you may have a look at the related articles on my homepage:
- Count Unique Values by Group in Column
- Sort List of datetime Objects in Python
- Convert pandas DataFrame Index to List & NumPy Array
- Python Programming Language
In this article you have learned how to get the amount of repeated elements in a list in the Python programming language. If you have any further questions, don’t hesitate to let me know in the comments section below.
Statistics Globe Newsletter