How To Find The Mode Of A List In Python

Finding the mode of a list is a common task when you are working with data or statistics in Python.

The mode is the most frequently occurring value or values in a data set. In this tutorial, we will go through how to find the mode of a list in Python, covering multiple techniques to achieve this, including using the built-in Python libraries and writing a custom function.

Step 1: Using the Python statistics module

Python includes a statistics module starting from version 3.4. To use this module to find the mode of a list in Python, first, we’ll have to import the module, then call the statistics.mode() function with our list as the argument.

If the list contains multiple modes (i.e., more than one value has the highest frequency), the statistics.mode() function will raise a StatisticsError.

Output

no unique mode; found 2 equally common values

Step 2: Using the collections Counter class

To find multiple modes in a list, we can use the Counter class from the collections module. The Counter class allows us to count the frequency of the elements in a list and find multiple modes if they exist.

Here’s how to use the Counter class to find the mode of a list in Python:

This function works even if the list contains multiple modes:

Output

[3, 4]

Full Code

Output

Using statistics module: 4
Using Counter class: [4]
Multiple modes: [3, 4]

Conclusion

In this tutorial, we’ve learned how to find the mode of a list in Python using the built-in statistics module and the Counter class from the collections module. Additionally, we demonstrated how to handle cases where multiple modes exist within the data set. With these tools, you can now analyze the most frequently occurring values in your Python projects!