Find the most/least common element in a List in Python

avatar
Borislav Hadzhiev

Last updated: Apr 10, 2024
8 min

banner

# Table of Contents

  1. Find the most common element in a List in Python
  2. Get the least common element in a List in Python
  3. Find the most frequent value in a Dictionary in Python

# Find the most common element in a List in Python

To find the most common element in a list:

  1. Use the collections.Counter() class to create a counter object.
  2. Use the most_common() method to get the most common element in the list.
main.py
from collections import Counter a_list = ['one', 'one', 'one', 'two', 'two', 'three'] counter = Counter(a_list) most_common = counter.most_common(1)[0][0] print(most_common) # ๐Ÿ‘‰๏ธ one most_common_2 = counter.most_common(2) print(most_common_2) # ๐Ÿ‘‰๏ธ [('one', 3), ('two', 2)]

find most common element in list

The code for this article is available on GitHub

If you need to find the least common element in a list, click on the following subheading.

We used the collections.Counter class to count the occurrences of each list item.

The Counter class from the collections module is a subclass of the dict class.

The class is basically a mapping of key-count pairs.

main.py
from collections import Counter a_list = ['one', 'one', 'one', 'two', 'two', 'three'] counter = Counter(a_list) print(counter) # ๐Ÿ‘‰๏ธ Counter({'one': 3, 'two': 2, 'three': 1})

Counter objects implement a most_common() method that returns a list of the N most common elements and their counts from the most common to the least.

main.py
from collections import Counter a_list = ['one', 'one', 'one', 'two', 'two', 'three'] counter = Counter(a_list) most_common = counter.most_common(1)[0][0] print(most_common) # ๐Ÿ‘‰๏ธ one # ๐Ÿ‘‡๏ธ [('one', 3)] print(counter.most_common(1))

Python indexes are zero-based, so the first item in a list has an index of 0, and the last item has an index of -1 or len(my_list) - 1.

If no argument is provided to the most_common method, it lists all element counts.

The method returns a list of tuples where the first element is the list item and the second is the number of occurrences.

# Finding the most common N elements in a list

You can also use this approach to get the most common N elements in a list.

main.py
from collections import Counter a_list = ['one', 'one', 'one', 'two', 'two', 'three'] counter = Counter(a_list) n = 2 most_common_n = counter.most_common(n) print(most_common_n) # ๐Ÿ‘‰๏ธ [('one', 3), ('two', 2)]

finding most common n elements in list

The code for this article is available on GitHub

We passed 2 as an argument to the most_common() method, so it returned the most common 2 elements in the list.

Alternatively, you can use the max() function.

# Find the most common element in a List using max()

This is a four-step process:

  1. Use the max() function.
  2. Pass the key argument to the functions.
  3. Use the list.count() method to count the occurrences of each element.
  4. The max() function will return the most common element.
main.py
a_list = ['one', 'one', 'one', 'two', 'two', 'three'] most_common = max(set(a_list), key=a_list.count) print(most_common) # ๐Ÿ‘‰๏ธ one

find most common element in list using max

We used the max() function to get the most common element in a list.

The max function returns the largest item in an iterable or the largest of two or more arguments.

main.py
my_list = [15, 45, 30] result = max(my_list) print(result) # ๐Ÿ‘‰๏ธ 45

The max function also takes an optional key argument.

The key argument specifies a one-argument ordering function.

We used the set() class to convert the list to a set object to remove any duplicates.

You can imagine that:

  1. The list.count() method gets called with each element in the set.
  2. The method returns the number of times the element appears in the list.
  3. The max() function returns the most common list element.
main.py
a_list = ['one', 'one', 'one', 'two', 'two', 'three'] most_common = max(set(a_list), key=a_list.count) print(most_common) # ๐Ÿ‘‰๏ธ one

The list.count() method takes a value and returns the number of times the provided value appears in the list.

main.py
a_list = ['one', 'one', 'one', 'two', 'two', 'three'] print(a_list.count('one')) # ๐Ÿ‘‰๏ธ 3 print(a_list.count('two')) # ๐Ÿ‘‰๏ธ 2 print(a_list.count('abc')) # ๐Ÿ‘‰๏ธ 0

# Find the most common element in a List using statistics.mode()

Alternatively, you can use the statistics.mode() method.

The mode() method returns the single most common value in the provided iterable.

main.py
from statistics import mode a_list = ['one', 'one', 'one', 'two', 'two', 'three'] most_common = mode(a_list) print(most_common) # ๐Ÿ‘‰๏ธ one

find most common element in list using statistics mode

The code for this article is available on GitHub

The statistics.mode() method takes an iterable and returns the most common value in the iterable.

main.py
from statistics import mode a_list = ['one', 'one', 'one', 'two', 'two', 'three'] print(mode([1, 1, 1, 2, 2, 3])) # ๐Ÿ‘‰๏ธ 1 # ๐Ÿ‘‡๏ธ one print(mode(['one', 'one', 'one', 'two', 'two', 'three']))

If there are multiple values with the same frequency, the method returns the first encountered value.

If the provided iterable is empty, the method raises a StatisticsError exception.

Prior to Python v3.8, the statistics.mode() method raises a StatisticsError exception if there is no most common element in the iterable, e.g. if the top two have the same number of occurrences.

# Get the least common element in a List in Python

To get the least common element in a list:

  1. Use the collections.Counter() class to count the occurrences of each element.
  2. Use the most_common() method to get the most common elements and their counts.
  3. Access the result at index -1 to get the least common element.
main.py
from collections import Counter a_list = ['c', 'a', 'a', 'b', 'b', 'z', 'z', 'z'] # โœ… Get the least common element in a list least_common = Counter(a_list).most_common()[-1] print(least_common) # ๐Ÿ‘‰๏ธ ('c', 1) print(least_common[0]) # ๐Ÿ‘‰๏ธ 'c' # ------------------------------------------------- # โœ… Get the N least common elements in a list least_common_2_elements = Counter(a_list).most_common()[-2:] print(least_common_2_elements) # ๐Ÿ‘‰๏ธ [('b', 2), ('c', 1)]
The code for this article is available on GitHub

We used the collections.Counter class to count the occurrences of each list item.

The Counter class from the collections module is a subclass of the dict class.

The class is basically a mapping of key-count pairs.

main.py
from collections import Counter a_list = ['c', 'a', 'a', 'b', 'b', 'z', 'z', 'z'] # ๐Ÿ‘‡๏ธ Counter({'z': 3, 'a': 2, 'b': 2, 'c': 1}) print(Counter(a_list))

Counter objects implement a most_common() method that returns a list of the N most common elements and their counts from the most common to the least.

main.py
from collections import Counter a_list = ['c', 'a', 'a', 'b', 'b', 'z', 'z', 'z'] # ๐Ÿ‘‡๏ธ [('z', 3), ('a', 2), ('b', 2), ('c', 1)] print(Counter(a_list).most_common())

We didn't provide an argument for N, so the method returns all elements in the counter.

Elements that have equal counts are ordered by the first encountered value.

The last step is to access the list at index -1.

main.py
from collections import Counter a_list = ['c', 'a', 'a', 'b', 'b', 'z', 'z', 'z'] least_common = Counter(a_list).most_common()[-1] print(least_common) # ๐Ÿ‘‰๏ธ ('c', 1) print(least_common[0]) # ๐Ÿ‘‰๏ธ 'c'

Python indexes are zero-based, so the first item in a list has an index of 0, and the last item has an index of -1 or len(my_list) - 1.

Negative indices can be used to count backward, e.g. my_list[-1] returns the last item in the list and my_list[-2] returns the second to last item.

The list element at index -1 stores the least common item and its number of occurrences in the list.

# Find the N least common elements in a list

You can use list slicing if you need to get the N least common elements in the list.

main.py
from collections import Counter a_list = ['c', 'a', 'a', 'b', 'b', 'z', 'z', 'z'] least_common_2_elements = Counter(a_list).most_common()[-2:] print(least_common_2_elements) # ๐Ÿ‘‰๏ธ [('b', 2), ('c', 1)]
The code for this article is available on GitHub

The syntax for list slicing is my_list[start:stop:step].

The start index is inclusive and the stop index is exclusive (up to, but not including).

The slice my_list[-2:] starts at the second to last list item and goes to the end of the list.

# Find the most frequent value in a Dictionary in Python

To find the most frequent value in a dictionary:

  1. Use the dict.values() method to get a view of the dictionary's values.
  2. Use the collections.Counter() class to create a counter object.
  3. Use the most_common() method to get the most frequent value in the dictionary.
main.py
from collections import Counter my_dict = { 'a': 1, 'b': 1, 'c': 1, 'd': 2, 'e': 2, 'f': 3 } counter = Counter(my_dict.values()) most_common_value = counter.most_common(1)[0] print(most_common_value) # ๐Ÿ‘‰๏ธ (1, 3) print(most_common_value[0]) # ๐Ÿ‘‰๏ธ 1 most_common_values = counter.most_common(2) print(most_common_values) # ๐Ÿ‘‰๏ธ [(1, 3), (2, 2)]
If you need a solution without using any imports, scroll down to the next subheading.

The dict.values() method returns a new view of the dictionary's values.

main.py
from collections import Counter my_dict = { 'a': 1, 'b': 1, 'c': 1, 'd': 2, 'e': 2, 'f': 3 } # ๐Ÿ‘‡๏ธ dict_values([1, 1, 1, 2, 2, 3]) print(my_dict.values())

We used the collections.Counter class to count the occurrences of each value.

The Counter class from the collections module is a subclass of the dict class.

The class is basically a mapping of key-count pairs.

main.py
from collections import Counter my_dict = { 'a': 1, 'b': 1, 'c': 1, 'd': 2, 'e': 2, 'f': 3 } counter = Counter(my_dict.values()) print(counter) # ๐Ÿ‘‰๏ธ Counter({1: 3, 2: 2, 3: 1})

Counter objects implement a most_common() method that returns a list of the N most common elements and their counts from the most common to the least.

main.py
from collections import Counter my_dict = { 'a': 1, 'b': 1, 'c': 1, 'd': 2, 'e': 2, 'f': 3 } counter = Counter(my_dict.values()) most_common_value = counter.most_common(1)[0] print(most_common_value) # ๐Ÿ‘‰๏ธ (1, 3) print(most_common_value[0]) # ๐Ÿ‘‰๏ธ 1

Python indexes are zero-based, so the first item in a list has an index of 0, and the last item has an index of -1 or len(my_list) - 1.

If no argument is provided to the most_common method, it lists all element counts.

The method returns a list of tuples where the first element is the list item and the second is the number of occurrences.

# Find the N most common values in a Dictionary

You can also use this approach to get the most common N values in a dictionary.

main.py
from collections import Counter my_dict = { 'a': 1, 'b': 1, 'c': 1, 'd': 2, 'e': 2, 'f': 3 } counter = Counter(my_dict.values()) most_common_values = counter.most_common(2) print(most_common_values) # ๐Ÿ‘‰๏ธ [(1, 3), (2, 2)]
The code for this article is available on GitHub

We passed 2 as an argument to the most_common() method, so it returned the most common 2 dictionary values.

Alternatively, you can use the max function.

# Find the most frequent value in a Dictionary using max()

This is a four-step process:

  1. Use the max() function.
  2. Pass the key argument to the function.
  3. Use the list.count() method to count the occurrences of each value.
  4. The max() function will return the most common value.
main.py
my_dict = { 'a': 1, 'b': 1, 'c': 1, 'd': 2, 'e': 2, 'f': 3 } values = list(my_dict.values()) most_common_value = max(set(values), key=values.count) print(most_common_value) # ๐Ÿ‘‰๏ธ 1

We used the dict.values() method to get a view of the dictionary's values and converted the view object to a list.

The max() function returns the largest item in an iterable or the largest of two or more arguments.

main.py
my_list = [15, 45, 30] result = max(my_list) print(result) # ๐Ÿ‘‰๏ธ 45

The max function also takes an optional key argument.

The key argument specifies a one-argument ordering function.

We used the set() class to convert the list to a set object to remove any duplicates.

You can imagine that:

  1. The list.count() function gets called with each element in the set.
  2. The function returns the number of times the value appears in the list.
  3. The max() function returns the most common value.
main.py
my_dict = { 'a': 1, 'b': 1, 'c': 1, 'd': 2, 'e': 2, 'f': 3 } values = list(my_dict.values()) most_common_value = max(set(values), key=values.count) print(most_common_value) # ๐Ÿ‘‰๏ธ 1

The list.count() method takes a value and returns the number of times the provided value appears in the list.

main.py
my_dict = { 'a': 1, 'b': 1, 'c': 1, 'd': 2, 'e': 2, 'f': 3 } values = list(my_dict.values()) print(values) # ๐Ÿ‘‰๏ธ [1, 1, 1, 2, 2, 3] print(values.count(1)) # ๐Ÿ‘‰๏ธ 3 print(values.count(2)) # ๐Ÿ‘‰๏ธ 2 print(values.count('abc')) # ๐Ÿ‘‰๏ธ 0
The code for this article is available on GitHub

Which approach you pick is a matter of personal preference. I'd use the Counter class as I find the most_common method quite intuitive.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev