Stop 05 · Built-in Data StructuresTopics · 4/9

Sets

Part of the Python Roadmap

In short

Need to remove duplicates, check membership in a huge collection or find what two groups have in common? Sets do all of that in one line, and much faster than lists.

A set is an unordered collection of unique items. It removes duplicates and supports fast membership checks and set maths like union (|), intersection (&) and difference (-).

The jaadu stands at a decorated wedding gate with a register, waving one guest in while gently turning away an identical twin who already entered.

Think of it like this

The guest list at the wedding gate

The person at the gate keeps a register of who has entered. If your cousin walks in twice, their name isn't written twice. Asking 'is Priya here?' is instant. And comparing the bride's list with the groom's list shows who's on both. That register is a set.

Watch it happen

Turning a list of roll numbers into a set

12
0
7
1
12
2
3
3
7
4
21
5

1/4Attendance was marked twice for some students. The list has 6 entries.

The big ideas

What you need to know

Only unique items

Adding something that's already there does nothing. set(my_list) is the quickest way to deduplicate.

Fast membership

x in my_set is almost instant even for millions of items, while x in my_list checks one by one.

Set maths

a | b is union, a & b is intersection, a - b is what's in a but not b, and a ^ b is what's in exactly one.

No order, no index

Sets have no positions, so s[0] fails. Items must be hashable, so you can't put a list inside a set.

See it in code

Walk through the code

python
1python_club = {"Asha", "Rohan", "Meera", "Vikram"}2dance_club = {"Meera", "Sana", "Rohan", "Dev"}3 4print(python_club & dance_club)   # in both clubs5print(python_club | dance_club)   # in either club6print(python_club - dance_club)   # only in python club7 8python_club.add("Sana")9python_club.add("Asha")           # already there, no change10python_club.discard("Dev")        # no error if missing11print(len(python_club))           # 512 13emails = ["a@x.in", "b@x.in", "a@x.in", "c@x.in"]14unique = set(emails)15print(len(emails), len(unique))   # 4 316 17empty = set()                     # {} would make a dict18print("Rohan" in dance_club)      # True

1/5Curly braces with plain values (no colons) create sets.

Club members as sets: overlaps, combinations, adding safely and removing duplicate emails.

Save yourself the pain

Common mistakes

Oops

Writing s = {} to make an empty set.

Do this instead

{} is an empty dict. Use s = set().

Oops

Expecting set(['c', 'a', 'b']) to keep the original order.

Do this instead

Sets are unordered. If you need unique items in their first-seen order, use list(dict.fromkeys(items)).

Oops

Using remove() on something that might not be there.

Do this instead

remove() raises KeyError if the item is missing. discard() does not.

Your mission

Common friends finder

~15 min

Quick check

What is {1, 2, 3} - {2, 3, 4}?

Go deeper

  1. 1Remove duplicates from a list of city names by converting it to a set.
  2. 2Find students enrolled in both Python and SQL using intersection.
  3. 3Use a set instead of a list when you check 'is x in here?' many times.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge