October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

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

The shortest check is len(set(s)) == len(s). Here is when to use an early-exit loop or Counter instead, and how Unicode code points affect the result.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The shortest correct test is len(set(s)) == len(s). It returns True when no character repeats and False otherwise. The rest of this article covers when to use a different approach, and what “character” means for Unicode text.

The one-line answer

def all_unique(s: str) -> bool:
    return len(set(s)) == len(s)

all_unique("python")   # True
all_unique("hello")    # False (two "l")
all_unique("")         # True

Python’s tutorial defines a set as “an unordered collection with no duplicate elements.” Building a set from a string therefore discards repeats. If the set is as long as the string, nothing was discarded, so every character was unique. An empty string has nothing to repeat, so it returns True.

The expected running time is O(n) with O(k) extra memory, where n is the string length and k is the number of distinct characters. This is an average-case figure. CPython’s time-complexity reference lists average O(1) set insertion and membership, but warns that the worst case for hash tables can degrade to linear. So describe the bound as expected, not guaranteed.

Choosing an approach

Seen-set loop: stop at the first duplicate

def all_unique_early_exit(s: str) -> bool:
    seen = set()
    for char in s:
        if char in seen:
            return False
        seen.add(char)
    return True

This has the same expected O(n) time and O(k) memory. However, it returns as soon as it meets a repeat, so it can do far less work on a long string whose duplicate appears early. The one-liner always builds the full set first. Choose the loop when early exit matters, when you need custom handling (such as reporting the first repeated character), or when you are explaining the algorithm.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Counter: when you need to know which characters repeat

from collections import Counter

counts = Counter(s)
is_unique = all(n == 1 for n in counts.values())
repeated = [ch for ch, n in counts.items() if n > 1]

The collections documentation describes Counter as a tallying tool. It gives more information than a yes/no answer, but it is more machinery than the set comparison for a boolean-only task. Use it for questions like “how can I detect duplicate characters in a string?”, where the duplicates themselves matter.

Quick comparison

Approach Returns Early exit Gives counts Best for
len(set(s)) == len(s) Boolean No No Compact default check
Seen-set loop Boolean Yes No Long inputs, custom handling, teaching
Counter Counts, from which you derive anything No Yes Finding or reporting duplicates

What “character” means for Unicode text

A Python str is, per the language’s data model documentation, a sequence of values representing characters, more formally Unicode code points. So set(s) tests the uniqueness of code points, which is not always what a person sees as a character. Two consequences:

  • No normalization. An accented “é” can be one precomposed code point or an “e” followed by a combining accent. A set treats these as different, so two visually identical spellings are not detected as duplicates of each other.
  • Visible units can span several code points. A user-perceived character (a grapheme cluster) may be made of multiple code points, and iterating a str does not group them.

If canonically equivalent spellings should count as the same, normalize first:

import unicodedata

def all_unique_normalized(s: str) -> bool:
    s = unicodedata.normalize("NFC", s)
    return len(set(s)) == len(s)

If the requirement is uniqueness of visible characters, you must define and segment grapheme clusters explicitly, because plain str iteration won’t do it. For most exercises and interview questions, checking code points as shown above is the intended meaning.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Case sensitivity

The checks above treat “A” and “a” as different. If they should match, convert first, for example s.casefold(), and then run the test.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.