Python Tutorial 0/52 lessons ~6 min read Lesson 19
Sets
Sets are unordered collections of unique, hashable items — O(1) membership, union, intersection.
Course progress0%
Focus
9 guided sections
Practice signal
Examples included
Career prep
Foundation builder
Introduction
Sets are unordered collections of unique, hashable items — O(1) membership, union, intersection. Perfect for deduplication.
Understanding the topic
Core concepts to understand:
{1, 2, 3}orset().x in sis O(1) avg.- Operations:
|union,&intersect,-diff. frozensetis the immutable variant.
Syntax reference
Visual flow / code:
python
a = {1, 2, 3}b = {3, 4, 5}print(a | b) # {1,2,3,4,5}print(a & b) # {3}print(a - b) # {1, 2}print(a ^ b) # {1,2,4,5} symmetric diff# Deduplicateunique = set([1, 1, 2, 2, 3]) # {1,2,3}# Membership test (fast)if user_id in admin_set: ...
Execution workflow
1Sets Workflow
1 / 4Step 1
{1, 2, 3} or set().
Apply this step while implementing sets in real code.
Real-world use
Sets are the go-to for membership tests on large datasets. Replace x in big_list (O(n)) with x in big_set (O(1)).
Best practices
- Use sets for membership tests.
- Set ops for algebra over collections.
- frozenset for set-of-sets.
Common mistakes
- Set elements must be hashable — no lists/dicts inside.
Hands-on exercise
Interview preparation — practice these questions:
- Set vs list lookup time?
- What's a frozenset?
- Why must set items be hashable?
Summary
In summary: O(1) membership, dedup, set algebra. Hashable items only.
Ready to mark this lesson complete?Track your journey across the entire course.