find the mode of a list of numbers in python

To find the mode of a list of numbers in Python, you can use the statistics module that comes with Python's standard library.

Here's a code example using the statistics.mode() function:

main.py
import statistics

# define a list of numbers
numbers = [1, 2, 3, 3, 4, 4, 4, 5]

# calculate the mode
mode = statistics.mode(numbers)

# print the mode
print(mode)
165 chars
11 lines

Output:

main.py
4
2 chars
2 lines

In the example above, we first import the statistics module. We then define a list of numbers numbers. Using the statistics.mode() function, we calculate the mode of the list, and store it in the variable mode. Finally, we print the mode.

Note that the statistics.mode() function raises a statistics.StatisticsError if there is no unique mode.

gistlibby LogSnag