w3resource

Python: Find the item with maximum frequency in a given list

Python Collections: Exercise-20 with Solution

Write a Python program to find the item with maximum frequency in a given list.

Sample Solution:

Python Code:

from collections import defaultdict
def max_occurrences(nums):
    dict = defaultdict(int)
    for i in nums:
        dict[i] += 1
    result = max(dict.items(), key=lambda x: x[1]) 
    return result
nums = [2,3,8,4,7,9,8,2,6,5,1,6,1,2,3,2,4,6,9,1,2]
print ("Original list:")
print(nums)
print("\nItem with maximum frequency of the said list:")
print(max_occurrences(nums))

Sample Output:

Original list:
[2, 3, 8, 4, 7, 9, 8, 2, 6, 5, 1, 6, 1, 2, 3, 2, 4, 6, 9, 1, 2]

Item with maximum frequency of the said list:
(2, 5)

Flowchart:

Python Collections: Find the item with maximum frequency in a given list.

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to break a given list of integers into sets of a given positive number. Return true or false.
Next: Write a Python program to count most and least common characters in a given string.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz


Python: Tips of the Day

Inverts a dictionary with non-unique hashable values:

Example:

def tips_collect_dictionary(obj):
  inv_obj = {}
  for key, value in obj.items():
    inv_obj.setdefault(value, list()).append(key)
  return inv_obj
ages = {
  "Owen": 25,
  "Jhon": 25,
  "Pepe": 15,
}
print(tips_collect_dictionary(ages))

Output:

{25: ['Owen', 'Jhon'], 15: ['Pepe']}