w3resource

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:

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.