Python | Find frequency of largest element in list

Given a list, the task is to find the number of occurrences of the largest element of the list.

Examples:

Input : [1, 2, 8, 5, 8, 7, 8]
Output :3


Input : [2, 9, 1, 3, 4, 5]
Output :1

Method 1: The naive approach is to find the largest element present in the list using max(list) function, then iterating through the list using a for loop and find the frequency of the largest element in the list. Below is the implementation.



filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to find the
# frequncy of largest element
  
  
L = [1, 2, 8, 5, 8, 7, 8]
  
# find the largest element
largest = max(L)
  
# Counter variabLle to store the
# number of occurrences of largest
count = 0
  
  
for i in L:
      
    # If the value of i is 
    # equal to the largest element
    if(i == largest):
        count+= 1
          
print(count)

chevron_right


Output:

3

Method 2: Using collections.Counter()
Once initialized, counters are accessed just like dictionaries. Also, it does not raise the KeyValue error (if key is not present) instead the value’s count is shown as 0.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to find the
# frequency of largest element
  
import collections
  
L = [1, 2, 8, 5, 8, 7, 8]
  
# find the largest element
largest = max(L)
  
# Storing the occurrences of each
# element of list in res
res = collections.Counter(L)
  
print(res[largest])

chevron_right


Output:

3

Method 3: Using the dictionary
In this approach, the number of occurrences of each element is stored in a dictionary as a key-value pair, where key is the element and value is the frequency.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to find the
# frequency of largest element
  
  
L = [1, 2, 8, 5, 8, 7, 8]
d= {}
  
# find the largest element
largest = max(L)
  
for i in L:
    if i in d:
        d[i] += 1
    else:
        d[i] = 1
          
print(d[largest])

chevron_right


Output:

3



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.