Most Frequent Element

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this challenge, you are required to write a Python function that takes a list of integers as input and returns the most frequent element in the list.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/numeric_types("`Numeric Types`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-13697{{"`Most Frequent Element`"}} python/variables_data_types -.-> lab-13697{{"`Most Frequent Element`"}} python/numeric_types -.-> lab-13697{{"`Most Frequent Element`"}} python/lists -.-> lab-13697{{"`Most Frequent Element`"}} python/tuples -.-> lab-13697{{"`Most Frequent Element`"}} python/function_definition -.-> lab-13697{{"`Most Frequent Element`"}} python/data_collections -.-> lab-13697{{"`Most Frequent Element`"}} python/build_in_functions -.-> lab-13697{{"`Most Frequent Element`"}} end

Most Frequent Element

Write a Python function called most_frequent(lst) that takes a list of integers as input and returns the most frequent element in the list. If there are multiple elements that appear the same number of times and have the highest frequency, return the one that appears first in the list.

To solve this problem, you can follow these steps:

  1. Use set() to get the unique values in lst.
  2. Use max() to find the element that has the most appearances.

Your function should have the following signature:

def most_frequent(lst: List[int]) -> int:
def most_frequent(lst):
  return max(set(lst), key = lst.count)
most_frequent([1, 2, 1, 2, 3, 2, 1, 4, 2]) #2

Summary

In this challenge, you have learned how to find the most frequent element in a list of integers using Python. You have also learned how to use the set() and max() functions to solve this problem.

Other Python Tutorials you may like