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.