Concept
Set Comprehensions
Generate unique sets directly with curly braces `{expr for item in iterable}` without colons.
python
words = ["apple", "banana", "apple"]
first_letters = {w[0] for w in words}
print(first_letters) # {'a', 'b'}
# 102. Set Comprehensions Generate unique sets directly with curly braces `{expr for item in iterable}` without colons: ```python words = ["apple", "banana", "apple"] first_letters = {w[0] for w in words} print(first_letters) # {'a', 'b'} ``` Set comprehensions automatically hash and deduplicate incoming results in memory. If five items evaluate to the same value, only one stays.
Checkpoint
How does a set comprehension handle duplicate evaluated results?
Practice
From `raw = [1, 2, -1, 2, -1]`, generate a set of their absolute values using `{abs(x) for x in raw}`. Print the set.
01
Tap code blocks below to assemble
Available Blocks