Set Comprehensions

Creating sets with comprehension syntax

Interview Relevant: Pythonic code

Set Comprehensions

Create sets using comprehension syntax.

Code Examples

Set comprehensions and patterns.

python
1# Basic set comprehension
2squares = {x**2 for x in range(10)}
3
4# With condition
5evens = {x for x in range(20) if x % 2 == 0}
6
7# From string (unique chars)
8unique_chars = {c for c in "hello world"}
9# {'h', 'e', 'l', 'o', ' ', 'w', 'r', 'd'}
10
11# Common interview pattern: find duplicates
12def find_duplicates(lst):
13    seen = set()
14    duplicates = set()
15    for item in lst:
16        if item in seen:
17            duplicates.add(item)
18        seen.add(item)
19    return duplicates
20
21# Or with comprehension
22nums = [1, 2, 2, 3, 3, 3]
23seen = set()
24dups = {x for x in nums if x in seen or seen.add(x)}

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In