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 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:

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

Python Code Editor:

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 Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.