A set in Python is an unordered collection of unique elements. Sets are perfect when you want to eliminate duplicates or perform mathematical set operations like union, intersection, and difference.
In this tutorial, you’ll learn:
-
What sets are
-
How to create and use them
-
Set operations and methods
-
Common use cases
-
Tips and pitfalls
What Is a Set?
A set is:
-
Unordered (no indexing)
-
Unchangeable (elements can't be changed, but items can be added/removed)
-
No duplicate elements
Creating a Set
my_set = {1, 2, 3}
print(my_set) # {1, 2, 3}
Creating an Empty Set
Important:
{}
creates an empty dictionary, not a set.
empty_set = set()
Mixed Data Types Allowed
mixed_set = {"apple", 42, True}
Accessing Set Items
Since sets are unordered, you can’t access items by index.
Instead, loop through:
for item in my_set:
print(item)
Set Methods
Method | Description | Example |
---|---|---|
add() |
Adds a single item | my_set.add(4) |
update() |
Adds multiple items | my_set.update([4, 5]) |
remove() |
Removes item, errors if not found | my_set.remove(2) |
discard() |
Removes item, no error if not found | my_set.discard(99) |
pop() |
Removes a random item | my_set.pop() |
clear() |
Empties the set | my_set.clear() |
copy() |
Copies the set | new_set = my_set.copy() |
Set Operations
Sets shine in performing mathematical operations:
✅ Union
Combines all unique elements from both sets.
a = {1, 2, 3}
b = {3, 4, 5}
print(a.union(b)) # {1, 2, 3, 4, 5}
✅ Intersection
Common elements in both sets.
print(a.intersection(b)) # {3}
✅ Difference
Items in one set but not the other.
print(a.difference(b)) # {1, 2}
✅ Symmetric Difference
Items not common to both.
print(a.symmetric_difference(b)) # {1, 2, 4, 5}
Checking Set Relationships
Operation | Description | Example |
---|---|---|
issubset() |
Is a a subset of b ? |
a.issubset(b) |
issuperset() |
Is a a superset of b ? |
a.issuperset(b) |
isdisjoint() |
No common elements? | a.isdisjoint(b) |
❗ Duplicates are Automatically Removed
numbers = {1, 2, 2, 3, 4, 4}
print(numbers) # {1, 2, 3, 4}
Frozenset: Immutable Set
A frozenset
is a set that cannot be changed after creation.
frozen = frozenset([1, 2, 3])
# frozen.add(4) → ❌ Error
Useful when you need to use sets as dictionary keys or protect data from being modified.
Example: Remove Duplicates from a List
my_list = [1, 2, 2, 3, 4, 4, 5]
unique = list(set(my_list))
print(unique) # [1, 2, 3, 4, 5]
Example: Set Operations Demo
a = {1, 2, 3}
b = {3, 4, 5}
print("Union:", a | b)
print("Intersection:", a & b)
print("Difference:", a - b)
print("Symmetric Difference:", a ^ b)
Tips for Using Sets
-
Use sets to eliminate duplicates from lists.
-
Use
update()
instead of looping to add multiple elements. -
Use
discard()
instead ofremove()
if you're unsure if the item exists. -
Convert strings/lists to sets to do fast membership tests.
⚠️ Common Pitfalls
Pitfall | Explanation | Fix |
---|---|---|
{} creates dict |
Use set() for empty set |
empty = set() |
Unordered | You can’t access by index | Use a list if ordering matters |
remove() errors if item not found |
Use discard() instead |
my_set.discard("value") |
Sets can’t contain mutable types | Can’t add lists/dicts to a set | Use tuples/frozensets if needed |
Summary
Feature | Description |
---|---|
Type | set |
Ordered? | ❌ No |
Changeable? | ✅ Yes (items can be added/removed) |
Allows Duplicates? | ❌ No |
Use Case | Unique elements, fast membership testing |
✅ Practice Exercise
Task: Write a function that returns common items between two lists using sets.
def common_elements(list1, list2):
return list(set(list1) & set(list2))
a = [1, 2, 3, 4]
b = [3, 4, 5, 6]
print(common_elements(a, b)) # [3, 4]
What's Next?
Now that you’ve mastered sets, explore:
-
Dictionaries (key-value structures)
-
List comprehensions with sets
-
Performance comparison:
in
with lists vs. sets