A set is an unordered collection that automatically removes duplicates and offers fast membership testing. Sets are written with curly braces and support the familiar mathematical operations — union, intersection, and difference — for combining or comparing collections.
#how it works
1
Create with curly braces
{item1, item2, ...} — duplicates are dropped automatically.
2
Membership is fast
in checks are much quicker on a set than on a list of comparable size.
3
Add and remove single items
.add() inserts one item; .remove() deletes one, raising an error if it isn’t present.
4
Combine sets mathematically
Union (|) merges them; intersection (&) keeps shared items; difference (-) keeps items in one but not the other.
5
Empty sets need set()
{} on its own creates an empty dictionary, not an empty set.
#example
a = {1, 2, 3, 3, 2}
b = {2, 3, 4}
print(a)
print(a | b)
print(a & b)
print(a - b)
Output
{1, 2, 3}
{1, 2, 3, 4}
{2, 3}
{1}
1{1, 2, 3, 3, 2} automatically drops the duplicate values, leaving just {1, 2, 3}.
2a | b (union) combines every unique item from both sets.
3a & b (intersection) keeps only the items present in both.
4a - b (difference) keeps only the items in a that aren't also in b.
#use cases
Removing duplicates from a list quickly, by converting it to a set and back
Fast membership checks, like validating a user's role against a set of allowed roles
Comparing two collections to find shared or unique items, such as common tags between two posts
Set operations for tasks like finding mutual friends or overlapping permissions
Practice Python interview questions
Every Python lesson maps to the matching interview topic, with answers written for current Python versions.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses →Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free →Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books →