Data StructuresTopic 11 of 221 min read
Sets
Unordered collections of unique items — and the math-style operations that come with them.
Watch the lesson
1 video on CodeWithMunnaX
A set stores unique, unordered items — duplicates are automatically dropped, and there's no indexing (my_set[0] doesn't work, since order isn't guaranteed).
python
python
tags = {"python", "tutorial", "python", "beginner"}
print(tags) # {'python', 'tutorial', 'beginner'} -- duplicate dropped
print(len(tags)) # 3
tags.add("2024")
tags.discard("tutorial") # remove if present, no error if missingAn empty {} creates a dict, not a set — for an empty set you must write set().
Why use a set?
- Deduplication — turn a list with duplicates into unique values fast:
unique = list(set(my_list)). - Fast membership checks —
x in my_setis on average O(1), much faster thanx in my_listfor large collections. - Set math — union, intersection, difference, exactly like set theory in math class.
python
python
watched = {"Intro", "Variables", "Loops"}
recommended = {"Loops", "Functions", "Decorators"}
print(watched | recommended) # union: all unique videos from both
print(watched & recommended) # intersection: videos in both sets -> {'Loops'}
print(watched - recommended) # difference: watched but not recommended
print(watched ^ recommended) # symmetric difference: in exactly one, not bothDeduplicating a list while keeping it simple
python
python
views_log = [120, 340, 120, 500, 340, 120]
unique_views = list(set(views_log))
print(sorted(unique_views)) # [120, 340, 500] -- set() doesn't preserve order, so sort if order mattersKey points to remember
- Sets store unique, unordered items — duplicates are dropped automatically, and there's no indexing.
- {} creates an empty dict, not an empty set — use set() for that.
- x in a_set is much faster on average than x in a_list for large collections.
- | is union, & is intersection, - is difference, ^ is symmetric difference — same as set theory in math.
- list(set(my_list)) is the quick idiom to deduplicate a list, but it doesn't preserve the original order.
Try it yourself
Set math on two video playlists
Revision Flashcards
Tap a card to flip it and see the answer.
