Set comprehension

2 snippets in Python

PYPython

Set Comprehensions

PY · Comprehensions & Generators
Syntax
{expr for item in iterable if cond}
Example
sentence = "the quick brown fox jumps over the lazy dog"
word_lengths = {len(word) for word in sentence.split()}
print(sorted(word_lengths))
Output
[3, 4, 5]

Note Set comprehensions look like dict comprehensions but without the colon. They automatically deduplicate results.

Frequently asked questions

How does Python handle set comprehension?
Python covers this with 2 copy-ready snippets on this page. The "Set Comprehensions" snippet in Python uses `{expression for item in iterable if condition}`.
Which code does the Python example use?
The "Set Comprehensions" snippet uses `{expression for item in iterable if condition}`, from the Tuples & Sets section of the Python cheat sheet.
What other Python snippets are shown for "set comprehension"?
Besides "Set Comprehensions", this page also shows "Set Comprehensions".
Is there anything to watch out for?
Yes. For "Set Comprehensions": Set comprehensions automatically deduplicate results. Useful for extracting unique transformed values from a collection.