Python Tricks #13 - Find The Most Frequent Value In A List

Words
0
Reading
0 min
Listen
Play
7y
# Most frequent element in a list
>>> a = [1, 2, 3, 1, 2, 3, 2, 2, 4, 5, 1]
>>> print(max(set(a), key = a.count))
2

# Using Counter from collections

>>> from collections import Counter
>>> cnt = Counter(a)

>>> cnt
Counter({2: 4, 1: 3, 3: 2, 4: 1, 5: 1})

>>> print(cnt.most_common(3))
[(2, 4), (1, 3), (3, 2)]

Python Tricks #13 - Find The Most Frequent Value In A List | Ecency