How to Check if a String Contains All Unique Characters in Python?

In this tutorial, I will explain how to check if a string contains all unique characters in Python. As a Python developer, I came across a scenario where I needed to check if a string contains all unique characters. After researching different methods, I discovered several ways to accomplish this task efficiently. In this article, I will share my findings and provide examples and screenshots of executed example code.

Check if a String Contains All Unique Characters in Python

Python provides several ways to achieve this task efficiently. Let us see some important methods.

Read How to Check if a Variable Exists in Python?

Method 1: Use Set in Python

The simplest way to check for uniqueness is by using a set. A set in Python automatically removes duplicates, so comparing its size to the original string‘s length can determine if all characters are unique.

Example: Check uniqueness in a state name

def has_unique_chars(s):
    return len(s) == len(set(s))

state_name = "Texas"  # Example from the USA
print(has_unique_chars(state_name)) 

Output:

True

I have executed the above example code and added the screenshot below.

Check if a String Contains All Unique Characters in Python

All characters in "Texas" are unique when treated case-sensitively. For case-insensitive checks, the string can be normalized using lower().

Check out How to Check if a Variable is a Number in Python?

Method 2: Use Dictionary in Python

Another approach is to use a dictionary to count the occurrences of each character. If any character appears more than once, the string doesn’t have unique characters.

Example: Check uniqueness in a US city name

def has_unique_chars_dict(s):
    char_count = {}
    for char in s:
        if char in char_count:
            return False
        char_count[char] = 1
    return True

city_name = "Seattle"
print(has_unique_chars_dict(city_name))

Output:

False

I have executed the above example code and added the screenshot below.

How to Check if a String Contains All Unique Characters in Python

This method also determines that “Seattle” does not have all unique characters because e and t are repeated. It is slightly more verbose than using a set but can be useful for tracking character counts.

Read How to Check if a Variable is Empty in Python?

Method 3: Use Sort in Python

Sorting the string allows us to check consecutive characters for duplicates. If any adjacent characters are the same, the string does not contain all unique characters.

Example: Check uniqueness in a US landmark

def has_unique_chars_sorted(s):
    sorted_chars = sorted(s)
    for i in range(len(sorted_chars) - 1):
        if sorted_chars[i] == sorted_chars[i + 1]:
            return False
    return True

landmark = "Alcatraz"
print(has_unique_chars_sorted(landmark)) 

Output:

False

I have executed the above example code and added the screenshot below.

Check if a String Contains All Unique Characters in Python Use Sort

This method concludes that “Alcatraz” has all unique characters. Sorting makes this approach efficient for medium-sized strings but adds some overhead compared to sets.

Check out How to Check if a Variable is an Empty String in Python?

Method 4: Use List Comprehension in Python

We can use a Pythonic one-liner with list comprehension to check if each character appears only once in the string.

Example: Check uniqueness in a US national park name

def has_unique_chars_list_comprehension(s):
    return all(s.count(char) == 1 for char in s)

park_name = "Yellowstone"
print(has_unique_chars_list_comprehension(park_name))

Output:

False

The result shows “Yellowstone” does not have unique characters, as l and o are repeated. While concise, this method is less efficient for large strings due to repeated calls to count.

Check out How to Check if a Variable is a Byte String in Python?

Method 5: Use collections.counter Function

The Counter class from the collections module counts the frequency of characters in one pass. If all counts are 1, the string has unique characters.

Example: Check uniqueness in a US sports team name

from collections import Counter

def has_unique_chars_counter(s):
    char_counts = Counter(s)
    return all(count == 1 for count in char_counts.values())

team_name = "Lakers"
print(has_unique_chars_counter(team_name))

Output:

True

The function confirms that “Lakers” has all unique characters. This method is efficient for character frequency analysis and useful for larger strings.

Read How to Check if a Variable is Not None in Python?

Conclusion

In this tutorial, I have explained how to check if a string contains all unique characters in Python. We discussed some methods using set, dictionary, sort, list comprehension, and use of collection.counter function.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.