Set Comprehension for Unique Word Lengths in Python

Use a set comprehension to extract unique word lengths from a string, then sort and print the result.

Easy Python 3.9+ Aug 9, 2026 Comprehensions & generators 10 views 0 copies

Python code

6 lines
Python 3.9+
text = "hello world hello python programming"

word_lengths = {len(word) for word in text.split()}

print("Unique word lengths:", word_lengths)
print("Sorted:", sorted(word_lengths))

Output

stdout
Unique word lengths: {5, 7, 8}
Sorted: [5, 7, 8]

How it works

The text.split() method splits the string into a list of words, then the set comprehension {len(word) for word in ...} iterates over each word, computes its length, and inserts the length into a set. Sets automatically discard duplicates, leaving only unique lengths. The sorted() function returns a list of the lengths in ascending order, which is easier to read than the unordered set output.

Common mistakes

  • Forgetting to call `split()` so the string is iterated character by character, producing lengths like 1 for each char.
  • Using a list comprehension `[len(word) ...]` instead of a set, which keeps duplicates.
  • Assuming the set's iteration order is sorted; always call `sorted()` explicitly.

Variations

  1. Using a generator expression with `set()`: `set(len(word) for word in text.split())`.
  2. If you need to exclude punctuation, preprocess words with `re.findall(r'\w+', text)`.

Real-world use cases

  • Analyzing text complexity by measuring the variety of word lengths in a document.
  • Validating password strength by checking if user-provided inputs have a target set of length categories.
  • Summarizing log messages by counting distinct string lengths to detect abnormally long entries.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Comprehensions & generators

Related tutorials and quizzes for this topic.