Lesson 03
Set Comprehension — Unique Values from Comma-Separated Tokens
Build a Python set in one line with curly braces, split comma-separated tokens, cast to int, and drop duplicates automatically.
What you will learn
- Set syntax:
{expression for name in iterable} - Splitting on a comma delimiter
- Why duplicates disappear
- The difference from a list comprehension on the same tokens
This continues from List comprehension. Sets themselves are covered in Set creation.
The big idea
A set comprehension looks like a list comprehension, but uses curly braces and produces a set.
st = {int(val) for val in raw.split(",")}Classroom version:
print("Enter List of Values separated by comma:")
st = {int(val) for val in input().split(",")}Playground version — same comprehension, string instead of input():
raw = "10,2,10,4,22,2"
st = {int(val) for val in raw.split(",")}
print("Set of Element=", st)
print(type(st))split(",") uses a comma delimiter, matching the teaching example.
Duplicates
| Form | Result for 10,2,10,4 |
|---|---|
List [int(v) for v in ...] |
[10, 2, 10, 4] |
Set {int(v) for v in ...} |
{10, 2, 4} (order not guaranteed) |
The second 10 and extra 2 are stored once.
List vs set on the same data
raw = "10,2,10,4"
print([int(v) for v in raw.split(",")])
print({int(v) for v in raw.split(",")})Use a list when order and repeats matter. Use a set when you only need unique values.
Optional if
You can still filter:
raw = "10,-3,0,22"
positives = {int(v) for v in raw.split(",") if int(v) > 0}
print(positives)Common mistakes
Empty {} — that is a dict, not an empty set. Empty set is set().
Expecting insertion order — sets are not sequences; do not use st[0].
Forgetting split(",") — a single string "10,2" without split stays one token.
Interview cheat sheet
| Question | Answer |
|---|---|
| Set comprehension braces? | { expression for ... } |
| Duplicates? | Removed |
| Comma-separated text? | .split(",") |
| Type? | set |
Practice in the playground
- Change
rawto"5,5,5"— the set should have one element. - Print
len(st)vslen(lst)on the starter data. - Add
if int(val) > 3and see which values remain.
Next: Dict comprehension.
Loading playground…
Check your understanding
Set comprehension quiz
Which syntax is a set comprehension?
1 / 10