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:
Code:
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}")
Output:
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:

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.
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) 20
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
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