Find the most frequent character in a String in Python

avatar
Borislav Hadzhiev

Last updated: Apr 10, 2024
3 min

banner

# Table of Contents

  1. Find the most frequent character in a String in Python
  2. Find the most frequent character in a String using max()
  3. Find the most frequent character in a String using statistics.mode()

# Find the most frequent character in a String in Python

To find the most frequent character in a string:

  1. Use the collections.Counter() class to create a counter object.
  2. Use the most_common() method to get the most frequent character in the string.
main.py
from collections import Counter string = 'aaabbc' counter = Counter(string) # โœ… Find the most frequent character in a string most_frequent = counter.most_common(1)[0] print(most_frequent) # ๐Ÿ‘‰๏ธ ('a', 3) print(most_frequent[0]) # ๐Ÿ‘‰๏ธ 'a' # โœ… Find the N most frequent characters in a string most_frequent_2 = counter.most_common(2) print(most_frequent_2) # ๐Ÿ‘‰๏ธ [('a', 3), ('b', 2)]

find most frequent character in string

The code for this article is available on GitHub

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

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 string = 'aaabbc' counter = Counter(string) print(counter) # ๐Ÿ‘‰๏ธ Counter({'a': 3, 'b': 2, 'c': 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 string = 'aaabbc' counter = Counter(string) print(counter) # ๐Ÿ‘‰๏ธ Counter({'a': 3, 'b': 2, 'c': 1}) most_frequent = counter.most_common(1)[0] print(most_frequent) # ๐Ÿ‘‰๏ธ ('a', 3) print(most_frequent[0]) # ๐Ÿ‘‰๏ธ 'a'

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 character counts.

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

You can also use this approach to get the most common N characters in a string.

main.py
from collections import Counter string = 'aaabbc' counter = Counter(string) print(counter) # ๐Ÿ‘‰๏ธ Counter({'a': 3, 'b': 2, 'c': 1}) most_frequent_2 = counter.most_common(2) print(most_frequent_2) # ๐Ÿ‘‰๏ธ [('a', 3), ('b', 2)]

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

Alternatively, you can use the max() function.

# Find the most frequent character in a String using max()

This is a four-step process:

  1. Use the max() function.
  2. Pass the key argument to the functions.
  3. Use the str.count() method to count the occurrences of each character.
  4. The max() function will return the most common character.
main.py
string = 'aaabbc' most_common = max(set(string), key=string.count) print(most_common) # ๐Ÿ‘‰๏ธ 'a'

find most frequent character in string using max

The code for this article is available on GitHub

We used the max() function to get the most common character in a string.

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 string to a set object to remove any duplicates.

You can imagine that:

  1. The str.count() method gets called with each element in the set.
  2. The method returns the number of times the character appears in the string.
  3. The max() function returns the most common character.
main.py
string = 'aaabbc' most_common = max(set(string), key=string.count) print(most_common) # ๐Ÿ‘‰๏ธ 'a'

The str.count method returns the number of occurrences of a substring in a string.

main.py
print('bobby'.count('b')) # ๐Ÿ‘‰๏ธ 3 print('bobby'.count('x')) # ๐Ÿ‘‰๏ธ 0

# Find the most frequent character in a String 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 string = 'aaabbc' most_common = mode(string) print(most_common) # ๐Ÿ‘‰๏ธ 'a'

find most frequent character in string 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.

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.

# 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