Python Tutorial: Python Sets
A set in Python is an unordered, unindexed collection of unique items written inside curly braces ({...}). Sets automatically remove duplicate values and are ideal for membership testing and mathematical set operations like union, intersection, and difference.
1. Creating Sets & Duplicate Removal
If you pass duplicate values when creating a set, Python keeps only one copy of each unique element:
skills = {"Python", "SQL", "Git", "Python"}
print(skills) # {'Python', 'SQL', 'Git'} (order may vary)
print(len(skills)) # 3
# Note: {} creates an empty dict, NOT an empty set!
empty_set = set()
print(type(empty_set)) # <class 'set'>
print(skills) # {'Python', 'SQL', 'Git'} (order may vary)
print(len(skills)) # 3
# Note: {} creates an empty dict, NOT an empty set!
empty_set = set()
print(type(empty_set)) # <class 'set'>
2. Adding & Removing Set Items
Set items cannot be changed by index because sets are unordered, but you can add or remove items dynamically:
tools = {"VS Code", "Docker"}
tools.add("Linux") # Add single item
tools.update(["GitHub", "Bash"]) # Add multiple items
tools.remove("Docker") # Raises KeyError if item is missing
tools.discard("Kubernetes") # Safe remove: no error if missing
print(tools)
tools.add("Linux") # Add single item
tools.update(["GitHub", "Bash"]) # Add multiple items
tools.remove("Docker") # Raises KeyError if item is missing
tools.discard("Kubernetes") # Safe remove: no error if missing
print(tools)
3. Set Operations (Union, Intersection, Difference)
Sets make comparing two groups of items fast and expressive using methods or operators:
backend = {"Python", "SQL", "Docker"}
data_ai = {"Python", "Pandas", "SQL"}
print(backend | data_ai) # Union (all unique items)
print(backend & data_ai) # Intersection (common items)
print(backend - data_ai) # Difference (in backend, not in data_ai)
print(backend ^ data_ai) # Symmetric difference (in either, not both)
data_ai = {"Python", "Pandas", "SQL"}
print(backend | data_ai) # Union (all unique items)
print(backend & data_ai) # Intersection (common items)
print(backend - data_ai) # Difference (in backend, not in data_ai)
print(backend ^ data_ai) # Symmetric difference (in either, not both)
4. Membership Checking & Looping
Checking item in my_set in Python runs in average O(1) time, making sets much faster than lists for large membership checks:
allowed_roles = {"admin", "editor", "author"}
print("editor" in allowed_roles) # True
print("guest" in allowed_roles) # False
for role in allowed_roles:
print("Role:", role)
print("editor" in allowed_roles) # True
print("guest" in allowed_roles) # False
for role in allowed_roles:
print("Role:", role)
Important: Elements inside a regular
set must be hashable (immutable types like strings, numbers, and tuples — not lists or dictionaries).