Python Program to Find Mode of List
To find the mode of a list in Python, use
max(set(lst), key=lst.count) which returns the most frequent element in the list.Examples
Input[1, 2, 2, 3, 4]
Output2
Input[5, 5, 5, 6, 6, 7]
Output5
Input[10]
Output10
How to Think About It
To find the mode, count how many times each number appears in the list. The number that appears the most times is the mode. We can check each unique number's count and pick the one with the highest count.
Algorithm
1
Get the list of numbers.2
Find all unique numbers in the list.3
Count how many times each unique number appears.4
Select the number with the highest count.5
Return that number as the mode.Code
python
lst = [1, 2, 2, 3, 4] mode = max(set(lst), key=lst.count) print(mode)
Output
2
Dry Run
Let's trace the list [1, 2, 2, 3, 4] through the code to find the mode.
1
Create set of unique elements
set(lst) = {1, 2, 3, 4}
2
Count occurrences for each unique element
counts: 1->1, 2->2, 3->1, 4->1
3
Find element with max count
max count is 2 for element 2
4
Return mode
mode = 2
| Element | Count |
|---|---|
| 1 | 1 |
| 2 | 2 |
| 3 | 1 |
| 4 | 1 |
Why This Works
Step 1: Find unique elements
Using set() removes duplicates so we only check each number once.
Step 2: Count each element's frequency
The count() method counts how many times each number appears in the list.
Step 3: Select the most frequent element
The max() function with key=lst.count picks the element with the highest count.
Alternative Approaches
Using collections.Counter
python
from collections import Counter lst = [1, 2, 2, 3, 4] mode = Counter(lst).most_common(1)[0][0] print(mode)
This method is more efficient for large lists and directly gives the most common element.
Manual counting with dictionary
python
lst = [1, 2, 2, 3, 4] counts = {} for num in lst: counts[num] = counts.get(num, 0) + 1 mode = max(counts, key=counts.get) print(mode)
This approach manually counts frequencies and then finds the max, useful for understanding the process.
Complexity: O(n^2) time, O(n) space
Time Complexity
Using max(set(lst), key=lst.count) causes count() to run for each unique element, leading to O(n^2) in worst case.
Space Complexity
Extra space is used for the set of unique elements, which is O(n) in the worst case.
Which Approach is Fastest?
Using collections.Counter is O(n) time and O(n) space, making it faster and better for large lists.
| Approach | Time | Space | Best For |
|---|---|---|---|
| max with count | O(n^2) | O(n) | Small lists, simple code |
| collections.Counter | O(n) | O(n) | Large lists, performance |
| Manual dictionary count | O(n) | O(n) | Learning frequency counting |
Use
collections.Counter for a clean and efficient way to find the mode.Beginners often forget to handle multiple modes or assume the list is sorted.