all Python 3Sets (set)function
Set comprehensions
comprehension
A set comprehension builds a set the same way a list comprehension builds a list, but with curly braces. Duplicates are removed automatically.
Syntax
{expr for var in iterable [if cond]}
Curly braces are shared with dicts: a colon inside turns the expression into a dict comprehension, and there is no literal for an empty set — {} is a dict, so use set(). The result has no defined order, so wrap it in sorted() when the output must be stable, and every produced item has to be hashable — a set of lists will not build.
Examples
squares = {x**2 for x in range(6)}
print(sorted(squares))
# → [0, 1, 4, 9, 16, 25]
evens = {x for x in range(10) if x % 2 == 0}
print(evens)
# → {0, 2, 4, 6, 8}
words = ['hello', 'world', 'hello', 'python']
unique_len = {len(w) for w in words}
print(unique_len)
# → {5, 6} (уникальные длины)
unique_first = {w[0] for w in words}
print(sorted(unique_first))
# → ['h', 'p', 'w'] (у множества строк порядок не определён, поэтому сортируем)
no_vowels = {c for c in 'hello' if c not in 'aeiou'}
print(sorted(no_vowels))
# → ['h', 'l']
See also
Open in the full glossarydocs.python.orgReport an inaccuracy