Count the number of unique characters in a String in Python

avatar

Borislav Hadzhiev

Last updated: Sep 22, 2022

banner

Photo from Unsplash

Count the number of unique characters in a String in Python #

To count the number of unique characters in a string:

  1. Use the set() class to convert the string to a set of unique characters.
  2. Use the len() function to get the number of unique characters in the string.
main.py
my_str = 'bobby' # ✅ using set() result = len(set(my_str)) print(result) # 👉️ 3 # ------------------------------- # ✅ using dict.fromkeys() result = len(dict.fromkeys(my_str)) print(result) # 👉️ 3

The first example uses the set() class to count the number of unique characters in a string.

The set() class takes an iterable optional argument and returns a new set object with elements taken from the iterable.

main.py
my_str = 'bobby' print(set(my_str)) # 👉️ {'y', 'b', 'o'}
Set objects store an unordered collection of unique elements, so converting the string to a set removes all duplicate characters.

The last step is to use the len() function to get the total count.

main.py
my_str = 'bobby' result = len(set(my_str)) print(result) # 👉️ 3

The len() function returns the length (the number of items) of an object.

The argument the function takes may be a sequence (a string, tuple, list, range or bytes) or a collection (a dictionary, set, or frozen set).

If you need to get the unique characters in the string, use the str.join() method instead of the len() function.

main.py
my_str = 'bobby' result = ''.join(set(my_str)) print(result) # 👉️ byo

The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

The string the method is called on is used as the separator between the elements.

Alternatively, you can use the dict.fromkeys() method.

Count the number of unique characters in a String using dict.fromkeys() #

To count the number of unique characters in a string:

  1. Use the dict.fromkeys() method to create a dictionary from the string.
  2. Use the len() function to get the number of unique characters in the string.
main.py
my_str = 'bobby' result = len(dict.fromkeys(my_str)) print(result) # 👉️ 3

The dict.fromkeys method takes an iterable and a value and creates a new dictionary with keys from the iterable and values set to the provided value.

main.py
my_str = 'bobby' # 👇️ {'b': None, 'o': None, 'y': None} print(dict.fromkeys(my_str))

Dictionary keys are unique, so any duplicate characters get removed.

If you need to get the unique characters in the string, use the str.join() method instead of the len() function.

main.py
my_str = 'bobby' result = ''.join(dict.fromkeys(my_str).keys()) print(result) # 👉️ boy

We used the dict.keys() method to get a view of the dictionary's keys and joined the object into a string.

Dictionaries preserve the insertion order of keys in Python 3.7 and more recent versions.

Alternatively, you can use a simple for loop.

Count the number of unique characters in a String using for loop #

To count the number of unique characters in a string:

  1. Declare a new variable that stores an empty list.
  2. Use a for loop to iterate over the string.
  3. Use the list.append() method to append all unique characters to the list.
  4. Use the len() function to get the length of the list.
main.py
my_str = 'bobby' unique_chars = [] for char in my_str: if char not in unique_chars: unique_chars.append(char) print(len(unique_chars)) # 👉️ 3 print(unique_chars) # 👉️ ['b', 'o', 'y']

We used a for loop to iterate over the string.

On each iteration, we use the not in operator to check if the character is not present in the list.

If the condition is met, we use the list.append() method to append the character to the list.

The in operator tests for membership. For example, x in l evaluates to True if x is a member of l, otherwise it evaluates to False.

x not in l returns the negation of x in l.

The list.append() method adds an item to the end of the list.

main.py
my_list = ['bobby', 'hadz'] my_list.append('com') print(my_list) # 👉️ ['bobby', 'hadz', 'com']

The last step is to use the len() function to get the length of the list of unique characters.

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.