Sets
Unordered collections of unique items — and the math-style operations that come with them.
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).
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 missing
An 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.
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 both
Deduplicating a list while keeping it simple
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.
Set math on two video playlists
Revision Flashcards
Tap a card to flip it and see the answer.