Skip to main content
MahiDev — Learn. Build. Become AI-ready.

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.

Intermediate25 min

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.

python
st = {int(val) for val in raw.split(",")}

Classroom version:

python
print("Enter List of Values separated by comma:")
st = {int(val) for val in input().split(",")}

Playground version — same comprehension, string instead of input():

python
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

Tokens 10 2 10 4 become set 10 2 4
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

python
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:

python
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

  1. Change raw to "5,5,5" — the set should have one element.
  2. Print len(st) vs len(lst) on the starter data.
  3. Add if int(val) > 3 and see which values remain.

Next: Dict comprehension.

Loading playground…

Check your understanding

Set comprehension quiz

Which syntax is a set comprehension?

1 / 10