Menu Close

How to find the most common element in a list with Python?

Sometimes, we want to find the most common element in a list with Python.

In this article, we’ll look at how to find the most common element in a list with Python.

How to find the most common element in a list with Python?

To find the most common element in a list with Python, we can use the max function with the key argument.

For instance, we write

def most_common(lst):
    return max(set(lst), key=lst.count)

to create the most_common function that calls max with the list lst items in a set.

And the key argument is set to lst.count to get the count of each item in the list.

Conclusion

To find the most common element in a list with Python, we can use the max function with the key argument.

Posted in Python, Python Answers