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.
Python code
6 linestext = "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
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
- Using a generator expression with `set()`: `set(len(word) for word in text.split())`.
- 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
More from Comprehensions & generators
- Batch Rows in Chunks with a Generator in Python easy
- Build a Generator Pipeline in Python: Filter Then Map medium
- Build a lazy generator to read file lines in Python easy
- Chunk an Iterable into Batches with a Generator in Python easy
- Convert Data in Python with Comprehensions and Generators easy
- Count Data in Python with Comprehensions and Generators easy
Keep learning
Related tutorials and quizzes for this topic.