Python: Find the item with maximum frequency in a given list
20. Find the Item with the Highest Frequency in a List
Write a Python program to find the item with the highest frequency in a given list.
Sample Solution:
Python Code:
# Import the defaultdict class from the collections module
from collections import defaultdict
# Define a function 'max_occurrences' that finds the item with the maximum frequency in a list
def max_occurrences(nums):
# Create a defaultdict 'dict' to count the occurrences of items in 'nums'
dict = defaultdict(int)
# Loop through the items in 'nums' and increment their counts in 'dict'
for i in nums:
dict[i] += 1
# Find the item with the maximum count using 'max' and a key function
result = max(dict.items(), key=lambda x: x[1])
# Return the result
return result
# Create a list 'nums' with integer values
nums = [2, 3, 8, 4, 7, 9, 8, 2, 6, 5, 1, 6, 1, 2, 3, 2, 4, 6, 9, 1, 2]
# Print a message to indicate the display of the original list
print("Original list:")
# Print the content of 'nums'
print(nums)
# Print a message to indicate the display of the item with the maximum frequency
print("\nItem with the maximum frequency of the said list:")
# Call the 'max_occurrences' function and print the result
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:

For more Practice: Solve these Related Problems:
- Write a Python program to determine the most frequent element in a list using collections.Counter and output the element along with its count.
- Write a Python program to use a dictionary to count list elements and then identify the key with the maximum value.
- Write a Python program to iterate over a list and compare frequencies to find and print the item that appears the most.
- Write a Python program to implement a function that returns a tuple (element, count) representing the highest frequency item in a list.
Go to:
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.
Python Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.