beginner
Sets in Python
5 min read
Overview
A Set is an unordered collection of unique elements enclosed in curly braces {}. Sets automatically eliminate duplicates and offer lightning-fast $O(1)$ lookup speeds.
Learning Objectives
- Create sets and add/remove elements.
- Use sets to remove duplicate items from lists.
- Perform set operations: Union (
|), Intersection (&), Difference (-), and Symmetric Difference (^).
Concept Explanation
In simple words:
- Unordered: Items have no fixed position or index (you cannot access
s[0]). - Unique: Duplicate elements are automatically ignored.
- Fast Lookups: Checking if an item exists (
item in my_set) runs in constant time $O(1)$.
Code Examples
Example 1 — Creating Sets & Removing Duplicates
python
# Creating a set with duplicate entries
raw_user_ids = [101, 102, 101, 103, 102]
# Deduplicate by converting to a set
unique_ids = set(raw_user_ids)
print("Unique IDs:", unique_ids) # {101, 102, 103}
# Adding and removing elements
unique_ids.add(104)
unique_ids.remove(101)
print("Updated Set:", unique_ids)
Example 2 — Set Mathematics
python
set_a = {"python", "sql", "spark"}
set_b = {"python", "java", "scala"}
# Union (all items from both)
print("Union:", set_a | set_b)
# Intersection (common items)
print("Intersection:", set_a & set_b) # {'python'}
# Difference (in A but not B)
print("Difference:", set_a - set_b) # {'sql', 'spark'}
Common Mistakes
- Creating empty sets with
{}:{}creates an empty dictionary, not a set. Useset()for empty sets. - Trying to store mutable objects in sets: Sets can only store immutable (hashable) items like numbers, strings, or tuples. Storing a list in a set raises a
TypeError.
Best Practices
- Use sets whenever you need to filter duplicates or test membership across large datasets.