Chapter 39 of 54

Sets in Python

Imagine you're collecting the names of everyone who attended a workshop over three days. Many people came on more than one day, but you only want each name once. You also want to quickly check "Did Ravi attend?" and find out who came on both day 1 and day 2.

Python's set is built exactly for this. It stores only unique values, checks membership very fast, and supports the same union and intersection operations you learned in school maths.

What is a Set?

A set is an unordered collection of unique, hashable items, written with curly braces: {1, 2, 3}.

  • Unique – duplicates are removed automatically.

  • Unordered – items have no fixed position, so there are no indexes.

  • Mutable – you can add and remove items.

  • Items must be hashable – numbers, strings and tuples are fine; lists are not.

nums = {3, 1, 2, 3, 1}

print(nums)
print(len(nums))
print(type(nums))

Output:

{1, 2, 3}
3
<class 'set'>

We wrote five values, but the set kept only the three unique ones.

Note: Because sets are unordered, the order in which Python prints a set is not something you should rely on. For sets of strings, the printed order can even change every time you run the program. In this chapter, we often use sorted() to print sets in a predictable order.


Creating Sets

evens = {2, 4, 6}
from_list = set([1, 2, 2, 3, 3, 3])
letters = set("banana")
empty = set()

print(evens)
print(from_list)
print(sorted(letters))
print(empty)

Output:

{2, 4, 6}
{1, 2, 3}
['a', 'b', 'n']
set()

The Empty Set Trap

{} does not create an empty set. It creates an empty dictionary (the topic of the next chapter):

a = {}
b = set()

print(type(a))
print(type(b))

Output:

<class 'dict'>
<class 'set'>

Only Hashable Items Allowed

A set needs to compute a hash (a number calculated from the value) for every item, so items must be immutable. A list can change, so it can't go into a set. A tuple can:

points = {(0, 0), (1, 2)}
print(len(points))

bad = {[1, 2], [3, 4]}

Output:

2
TypeError: cannot use 'list' as a set element (unhashable type: 'list')

(Older Python versions show this as TypeError: unhashable type: 'list'.)


No Indexing

A set has no positions, so my_set[0] doesn't work:

nums = {10, 20, 30}

print(nums[0])

Output:

TypeError: 'set' object is not subscriptable

You can still loop over a set with for, or convert it to a list or a sorted list when you need positions.


Adding and Removing Items

add() and update()

nums = {1, 2}

nums.add(3)           # add one item
nums.add(2)           # already there, nothing happens
nums.update([4, 5])   # add many items from any iterable

print(nums)

Output:

{1, 2, 3, 4, 5}

remove() vs discard()

Both delete an item. The difference is what happens when the item is missing:

nums = {1, 2, 3}

nums.discard(10)   # missing: silently does nothing
nums.discard(1)
print(nums)

nums.remove(10)    # missing: raises an error

Output:

{2, 3}
KeyError: 10

pop() and clear()

pop() removes and returns an arbitrary item. Since a set has no order, you can't choose which one. Use it only when you don't care which item you get. clear() empties the set.

tasks = {7, 8, 9}

item = tasks.pop()
print(len(tasks))

tasks.clear()
print(tasks)

Output:

2
set()

Fast Membership Testing

Checking x in my_set is one of the biggest reasons to use a set. A list checks items one by one, which takes O(n) time. A set jumps straight to where the item would be stored using its hash, which takes O(1) time on average.

List:  is 7 in [3, 9, 1, 7, 5]?   check 3 → 9 → 1 → 7 ✓   (one by one)
Set:   is 7 in {3, 9, 1, 7, 5}?   hash(7) → go to its slot → ✓   (direct)
blocked_users = {"spam_bot", "troll42", "fake_acc"}

username = "troll42"

if username in blocked_users:
    print("Access denied")
else:
    print("Welcome")

Output:

Access denied

For a list of a few items the difference is tiny, but with thousands of items checked again and again, a set is dramatically faster.


Set Operations

Let's say these students joined two clubs:

coding = {"Asha", "Ravi", "Neha", "Kiran"}
music = {"Neha", "Kiran", "Arjun"}
      coding                music
   ┌────────────┬──────┬──────────┐
   │ Asha  Ravi │ Neha │  Arjun   │
   │            │Kiran │          │
   └────────────┴──────┴──────────┘
      only coding  both  only music

Union – Everyone in Either Club

coding = {"Asha", "Ravi", "Neha", "Kiran"}
music = {"Neha", "Kiran", "Arjun"}

print(sorted(coding | music))
print(sorted(coding.union(music)))

Output:

['Arjun', 'Asha', 'Kiran', 'Neha', 'Ravi']
['Arjun', 'Asha', 'Kiran', 'Neha', 'Ravi']

Intersection – In Both Clubs

coding = {"Asha", "Ravi", "Neha", "Kiran"}
music = {"Neha", "Kiran", "Arjun"}

print(sorted(coding & music))
print(sorted(coding.intersection(music)))

Output:

['Kiran', 'Neha']
['Kiran', 'Neha']

Difference – In the First but Not the Second

coding = {"Asha", "Ravi", "Neha", "Kiran"}
music = {"Neha", "Kiran", "Arjun"}

print(sorted(coding - music))   # only coding
print(sorted(music - coding))   # only music

Output:

['Asha', 'Ravi']
['Arjun']

Unlike union and intersection, the order matters here: a - b is not the same as b - a.

Symmetric Difference – In Exactly One Club

coding = {"Asha", "Ravi", "Neha", "Kiran"}
music = {"Neha", "Kiran", "Arjun"}

print(sorted(coding ^ music))
print(sorted(coding.symmetric_difference(music)))

Output:

['Arjun', 'Asha', 'Ravi']
['Arjun', 'Asha', 'Ravi']

Operation

Operator

Method

Result

Union

a | b

a.union(b)

Items in a or b

Intersection

a & b

a.intersection(b)

Items in both

Difference

a - b

a.difference(b)

Items in a, not in b

Symmetric difference

a ^ b

a.symmetric_difference(b)

Items in exactly one

One small difference: the operators need both sides to be sets, but the methods accept any iterable:

a = {1, 2, 3}

print(a.union([3, 4]))   # a list is fine here
print(a | [3, 4])        # but not here

Output:

{1, 2, 3, 4}
TypeError: unsupported operand type(s) for |: 'set' and 'list'

Each operation also has an "update" version that changes the set in place, such as a |= b, a &= b, a -= b and a ^= b.


Subsets, Supersets and Disjoint Sets

required = {"python", "sql"}
skills = {"python", "sql", "git", "dsa"}
design = {"figma", "photoshop"}

print(required.issubset(skills))     # is every item of required in skills?
print(required <= skills)            # same thing, as an operator
print(skills.issuperset(required))   # does skills contain all of required?
print(skills.isdisjoint(design))     # no common items at all?

Output:

True
True
True
True

frozenset – An Immutable Set

A frozenset is a set that can't be changed after creation. Because it's immutable, it's hashable, so it can be stored inside another set (or used as a dictionary key).

vowels = frozenset("aeiou")

print("e" in vowels)
print(len(vowels))

vowels.add("y")

Output:

True
5
AttributeError: 'frozenset' object has no attribute 'add'

Practical Examples

Removing Duplicates from a List

roll_numbers = [104, 101, 104, 102, 101, 103]

unique = sorted(set(roll_numbers))

print(unique)

Output:

[101, 102, 103, 104]

Remember that converting to a set loses the original order. If you need to keep the first-seen order, you'll see a neat trick with dictionaries in the next chapter.

Counting Unique Words

sentence = "the cat and the dog and the bird"

words = sentence.split()
unique_words = set(words)

print(len(words), "words in total")
print(len(unique_words), "unique words")

Output:

8 words in total
5 unique words

Finding Common Elements (Interview Classic)

"Find the elements common to two arrays" can be solved with two nested loops in O(n × m) time, or with sets in O(n + m) on average:

a = [1, 4, 6, 8, 10]
b = [2, 4, 8, 9]

common = set(a) & set(b)

print(sorted(common))

Output:

[4, 8]

Time Complexity

Operation

Average Time

x in s, add(), remove(), discard()

O(1)

a | b (union)

O(len(a) + len(b))

a & b (intersection)

O(min(len(a), len(b)))

a - b (difference)

O(len(a))

set(list)

O(n)

These are average times. In rare worst cases (many items with colliding hashes), operations can degrade to O(n), but in everyday code you can treat set lookups as O(1).


Common Mistakes

  • Using {} for an empty set. It creates a dictionary. Use set().

  • Expecting a fixed order or trying to index a set. Use sorted(s) when you need order.

  • Using set("hello") to store a word. It splits the string into characters. Use {"hello"} instead.

  • Putting lists inside a set. Convert them to tuples first.

  • Using remove() when the item might be missing. Use discard() to avoid a KeyError.

List vs Tuple vs Set

Feature

List

Tuple

Set

Syntax

[1, 2]

(1, 2)

{1, 2}

Ordered / indexable

Yes

Yes

No

Duplicates

Allowed

Allowed

Not allowed

Mutable

Yes

No

Yes (frozenset: no)

x in ...

O(n)

O(n)

O(1) average

Final Takeaway

A set stores unique items with no order. Use it whenever you need to remove duplicates, check membership quickly, or compare groups using union, intersection and difference.

Practice: Given two strings, print the letters that appear in both of them, in alphabetical order. Then print the letters that appear in only one of them.