4. Most frequent item in list
Use Counter when you need frequencies. It is clearer and scales better than repeatedly calling list.count.
Repeated list.count scans the same data over and over, which hides both intent and cost. Counter says you are computing frequencies once and then querying them.
4.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
4.2. Do this
1from collections import Counter
2
3nums = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
4num, freq = Counter(nums).most_common(1)[0]