12. Most frequent item in list
Use max
with set
to find the most frequent item in a list.
12.1. Don’t do this
1nums = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
2d = {}
3for num in nums:
4 if num not in d:
5 d[num] = 0
6 d[num] += 1
7
8num, freq = None, None
9for n, f in d.items():
10 if freq is None or f > freq:
11 num = n
12 freq = f
12.2. Do this
1nums = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
2num = max(set(nums), key=nums.count)