Python Program: Counting common elements in a list

Python Counter Data Type: Exercise-2 with Solution

Write a Python program that creates a 'Counter' from a list of elements and print the most common elements along with their counts.

Sample Solution:


from collections import Counter

elements = [1, 2, 3, 4, 5, 11, 3, 3, 6, 7, 8, 9, 3, 10, 1]
element_counter = Counter(elements)

print("Most Common Elements:")
for element, count in element_counter.most_common():
    print(f"{element}: {count}")


Most Common Elements:
3: 4
1: 2
2: 1
4: 1
5: 1
11: 1
6: 1
7: 1
8: 1
9: 1
10: 1

In the exercise above, the "Counter" class is used to count the occurrences of each element in the given list. The "most_common()" method retrieves the most common elements along with their counts in descending order. After iterating through the most common elements, the program prints their counts.


Flowchart: Python Program: Counting common elements in a list.

Previous: Python Program: Counting letters in a string.
Next: Python Program: Counting vowels in a word.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.

Python: Tips of the Day

Summing a sequence of numbers (calculating the sum of zero to ten with skips):

>>> l = range(0,10,2)
>>> sum(l)


We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook