w3resource

Python: Find the most common element of a given list

Python Collections: Exercise-15 with Solution

Write a Python program to find the most common element in a given list.

Sample Solution:

Python Code:

# Import the Counter class from the collections module
from collections import Counter

# Create a list 'language' containing programming language names
language = ['PHP', 'PHP', 'Python', 'PHP', 'Python', 'JS', 'Python', 'Python', 'PHP', 'Python']

# Print a message to indicate the display of the original list
print("Original list:")

# Print the content of the 'language' list
print(language)

# Create a Counter object 'cnt' to count the occurrences of each language in the list
cnt = Counter(language)

# Print a message to indicate the display of the most common element in the list
print("\nMost common element of the said list:")

# Find and print the most common element (programming language) in the list
# Note: In this case, it returns the first most common element
print(cnt.most_common(1)[0][0]) 

Sample Output:

Original list:
['PHP', 'PHP', 'Python', 'PHP', 'Python', 'JS', 'Python', 'Python', 'PHP', 'Python']

Most common element of the said list:
Python

Flowchart:

Flowchart - Python Collections: Find the most common element of a given list.

Python Code Editor:

Previous: Write a Python program to rotate a Deque Object specified number (negative) of times.
Next: Write a Python program to find the second lowest total marks of any student(s) from the given names and marks of each student using lists and lambda. Input number of students, names and grades of each student.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/collections/python-collections-exercise-15.php