w3resource

Python: Most frequent element in a given list of numbers


Most Frequent Element in List

Write a Python program to get the most frequent element in a given list of numbers.

  • Use set() to get the unique values in nums.
  • Use max() to find the element that has the most appearances.

Sample Solution:

Python Code:

# Define a function named 'most_frequent' that finds the most frequently occurring item in a list.
def most_frequent(nums):
    return max(set(nums), key=nums.count)
    # Using 'set' to remove duplicates, then finding the item with the maximum count using the 'max' function.

# Test the 'most_frequent' function with different lists.
print(most_frequent([1, 2, 1, 2, 3, 2, 1, 4, 2]))
# Find the most frequently occurring item in the list. (Expected output: 2)

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("Item with the maximum frequency of the said list:")
print(most_frequent(nums))
# Find the most frequently occurring item in the list.

nums = [1, 2, 3, 1, 2, 3, 2, 1, 4, 3, 3]
print("\nOriginal list:")
print(nums)
print("Item with the maximum frequency of the said list:")
print(most_frequent(nums))
# Find the most frequently occurring item in the list. 

Sample Output:

2
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

Original list:
[1, 2, 3, 1, 2, 3, 2, 1, 4, 3, 3]
Item with maximum frequency of the said list:
3

Flowchart:

Flowchart: Most frequent element in a given list of numbers.

For more Practice: Solve these Related Problems:

  • Write a Python program to find the top two most frequent elements in a list along with their counts.
  • Write a Python program to determine if the most frequent element appears more than half the time in a list.
  • Write a Python program to find the most frequent element among those that occur at even indices.
  • Write a Python program to get the most frequent element from a list after filtering out values below a given threshold.

Go to:


Previous: Write a Python program to check if a given function returns True for at least one element in the list.
Next: Write a Python program to move the specified number of elements to the end of the given list.

Python Code Editor:

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.