Element with Largest Frequency in List (original) (raw)

Last Updated : 30 Jan, 2025

We are given a list we need to find the element with largest frequency in a list . **For example, we are having a list a = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] we need to find the element with most frequency which will be 4 in this case.

Using collections.Counter

Counter is a convenient way to count elements and get the most common one directly.

Python `

from collections import Counter

a = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] c = Counter(a) f = c.most_common(1)[0][0] # Get the element with highest frequency

print(f)

`

**Explanation:

Using max() with count()

We can use max() with count() to find the element with highest frequency by checking the count of each element.

Python `

a = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] m = max(set(a), key=a.count) # Find element with maximum count

print(m)

`

**Explanation:

**Using a Dictionary to Count Occurrences

We can manually count occurrences of each element and then find the one with largest count.

Python `

a = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] f = {}

for num in a: f[num] = f.get(num, 0) + 1

m = max(f, key=f.get) # Get the key with max value

print(m)

`

**Explanation:

**Using sorted()

We can sort list based on frequency and then pick the element with highest frequency.

Python `

a = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

Sort unique elements based on their frequency in descending order

m = sorted(set(a), key=lambda x: a.count(x), reverse=True)[0]

print(m)

`

**Explanation:

Similar Reads