To find the element with the maximum number of occurrences in a list in Python, you can use the Counter
class from the collections
module.
In this example,
Counter
class from the collections
module.data
with several elements.Counter
class to count the occurrences of each element in the list and store the result in count
.most_common(1)
method of the Counter
object, which returns a list of the most common elements and their counts.from collections import Counter
data = [1, 2, 2, 3, 3, 3, 4]
count = Counter(data)
most_common_element = count.most_common(1)[0][0]
print(f"Element with the maximum occurrences is: {most_common_element}")
Element with the maximum occurrences is: 3
In this example,
Counter
class from the collections
module.words
with several string elements.Counter
class to count the occurrences of each string in the list and store the result in count
.most_common(1)
method of the Counter
object, which returns a list of the most common elements and their counts.from collections import Counter
words = ["apple", "banana", "apple", "orange", "banana", "apple"]
count = Counter(words)
most_common_word = count.most_common(1)[0][0]
print(f"String with the maximum occurrences is: {most_common_word}")
String with the maximum occurrences is: apple
In this tutorial, we learned How to find the Element with Maximum Number of Occurrences in a List in Python language with well detailed examples.