How can I print the most common element of a list without importing a library?
l=[1,2,3,4,4,4]
So I want the output to be 4
.
How can I print the most common element of a list without importing a library?
l=[1,2,3,4,4,4]
So I want the output to be 4
.
You can get the unique values first:
l = [1, 2, 3, 4, 4, 4]
s = set(l)
then you can create list of (occurrences, value) tuples
freq = [(l.count(i), i) for i in s] # [(1, 1), (1, 2), (1, 3), (3, 4)]
get the "biggest" element (biggest number of occurrences, the biggest value if there are more than one with the same number of occurrences):
result = max(freq) # (3, 4)
and print the value:
print(result[1]) # 4
or as a "one-liner" way:
l = [1, 2, 3, 4, 4, 4]
print(max((l.count(i), i) for i in set(l))[1]) # 4
lst=[1,2,2,2,3,3,4,4,5,6]
from collections import Counter
Counter(lst).most_common(1)[0]
Counter(lst)
returns a dict
of element-occurence pairs. most_common(n)
returns the n most common elements from the dict, along with the number of occurences.