You have a list with 10,000 names and need to check if a specific name exists. You loop through the list — and wait. There has to be a faster way. There is. Python sets give you O(1) membership lookups instead of O(n) scans — and they automatically kill duplicates. Here is how to use them.
In this tutorial, you will learn to:
- Create and manipulate Python sets
- Use set methods: add, update, remove, discard, pop
- Perform set operations: union, intersection, difference, symmetric difference
- Understand when to use sets vs lists vs tuples
- Avoid common set pitfalls like mutability issues
Page Contents
What Is a Python Set?
A Python set is an unordered collection of unique elements. Sets are mutable — you can add and remove items — but they can only contain hashable (immutable) objects: strings, numbers, tuples. You cannot put a list or a dictionary inside a set. Behind the scenes, sets use a hash table, which is why membership tests are so fast. If you are coming from a language like Java or C++, think of a set as an unordered HashSet.
How to Create a Set in Python
Use curly braces {} with comma-separated values, or the set() constructor. Passing a list to set() is the fastest way to deduplicate a sequence — far faster than a loop.
# Create a set with curly braces
fruits = {"apple", "banana", "cherry"}
print(fruits)
# Output: {'apple', 'banana', 'cherry'} (order may vary)
# Create from a list — deduplicate automatically
names = ["Alice", "Bob", "Alice", "Charlie", "Bob"]
unique_names = set(names)
print(unique_names)
# Output: {'Alice', 'Bob', 'Charlie'} (order may vary)
# Empty set — you MUST use set(), not {}
empty = set()
print(empty)
# Output: set()
# set() from a string — each character becomes an element
letters = set("apple")
print(letters)
# Output: {'a', 'p', 'l', 'e'} (order may vary)
Warning:
{}creates an empty dict, not a set. Callingtype({})returns<class 'dict'>— a common mistake that leads to confusing errors later.
Set Size and Membership: len() and the in Operator
The len() function returns the count of unique elements. The in operator checks membership in O(1) time — the core advantage of sets over lists. For a list of 10,000 items, a membership check takes up to 10,000 comparisons. For a set, it takes exactly one hash lookup.
colors = {"red", "green", "blue"}
print(len(colors))
# Output: 3
print("green" in colors)
# Output: True
print("yellow" in colors)
# Output: False
Edge Cases: Empty Sets and Common Traps
A few behaviors worth knowing before you start using sets in production code:
# Empty set — pop() raises KeyError
empty = set()
try:
empty.pop()
except KeyError:
print("KeyError: pop from an empty set")
# Output: KeyError: pop from an empty set
# Adding None to a set is perfectly valid
has_nothing = {1, 2, None, "three"}
print(has_nothing)
# Output: {None, 1, 2, 'three'} (order may vary)
# Nested tuples work — they are hashable
nested = {(1, 2), (3, 4), (5, 6)}
print(nested)
# Output: {(1, 2), (3, 4), (5, 6)}
# Frozen sets (frozenset) are immutable — great for dict keys
immutable = frozenset([1, 2, 3])
print(immutable)
# Output: frozenset({1, 2, 3})
Python Set Methods: Add, Update, Remove
Sets are mutable. Here are the five essential methods for modifying them:
add() — Insert a Single Element
tools = {"hammer", "screwdriver"}
tools.add("wrench")
print(tools)
# Output: {'hammer', 'screwdriver', 'wrench'} (order may vary)
# Adding an existing element does nothing — no error
tools.add("hammer")
print(tools)
# Output: {'hammer', 'screwdriver', 'wrench'} (order may vary)
update() — Add Multiple Elements
Pass any iterable — a list, tuple, string, or another set. update() merges all elements in.
tools = {"hammer"}
tools.update(["wrench", "pliers"], ("saw",))
print(tools)
# Output: {'hammer', 'wrench', 'pliers', 'saw'} (order may vary)
remove() vs discard() — Deleting Elements
Both remove() and discard() delete an element from the set. The difference: remove() raises a KeyError if the element is missing. discard() does nothing if the element does not exist — no error.
colors = {"red", "green", "blue"}
# discard — safe, no error if missing
colors.discard("green")
print(colors)
# Output: {'red', 'blue'} (order may vary)
colors.discard("yellow") # No error
print(colors)
# Output: {'red', 'blue'} (order may vary)
# remove — raises KeyError if missing
colors.remove("red")
print(colors)
# Output: {'blue'}
try:
colors.remove("red")
except KeyError:
print("KeyError: 'red'")
# Output: KeyError: 'red'
pop() — Remove and Return an Arbitrary Element
set.pop() removes and returns an arbitrary element. Since sets are unordered, you cannot predict which element gets popped. On an empty set, pop() raises KeyError.
colors = {"red", "green", "blue"}
removed = colors.pop()
print(f"Removed: {removed}")
print(f"Remaining: {colors}")
# Output order varies since sets are unordered
clear() — Remove All Elements
colors = {"red", "green", "blue"}
colors.clear()
print(colors)
# Output: set()
Python Set Operations: Union, Intersection, Difference
Set operations are what make sets genuinely powerful. You can compute unions, intersections, differences, and more — either with methods or with operators.
Union — All Elements From Both Sets
set_a = {1, 2, 3}
set_b = {3, 4, 5}
# Method
result = set_a.union(set_b)
print(result)
# Output: {1, 2, 3, 4, 5}
# Operator
result = set_a | set_b
print(result)
# Output: {1, 2, 3, 4, 5}
Intersection — Elements in Both Sets
set_a = {1, 2, 3}
set_b = {3, 4, 5}
# Method
result = set_a.intersection(set_b)
print(result)
# Output: {3}
# Operator
result = set_a & set_b
print(result)
# Output: {3}
Difference — Elements in One Set But Not the Other
set_a = {1, 2, 3}
set_b = {3, 4, 5}
# Method
result = set_a.difference(set_b)
print(result)
# Output: {1, 2}
# Operator
result = set_a - set_b
print(result)
# Output: {1, 2}
Symmetric Difference — Elements in Either Set But Not Both
set_a = {1, 2, 3}
set_b = {3, 4, 5}
# Method
result = set_a.symmetric_difference(set_b)
print(result)
# Output: {1, 2, 4, 5}
# Operator
result = set_a ^ set_b
print(result)
# Output: {1, 2, 4, 5}
Set Comparison Methods
Python sets also give you methods to test relationships between sets:
a = {1, 2, 3}
b = {1, 2}
c = {1, 2, 3, 4}
print(a.isdisjoint(c)) # False — they share elements
print(b.issubset(a)) # True — all of b are in a
print(a.issuperset(b)) # True — a contains all of b
print(a.issubset(c)) # True
print(c.issuperset(a)) # True
Sets vs Lists vs Tuples — When to Use Which
| Property | set | list | tuple |
|---|---|---|---|
| Order | No | Yes | Yes |
| Duplicates | No — auto-removed | Yes | Yes |
| Mutable | Yes | Yes | No |
| Hashable container | No (unhashable) | No | Yes |
| Membership test | O(1) — fast | O(n) — slow | O(n) — slow |
| Index access | No | Yes — O(1) | Yes — O(1) |
Use a set when: You need fast membership tests, you want to eliminate duplicates automatically, or you are performing mathematical set operations. Python lists are ordered and allow duplicates — use them when order matters and duplicates are meaningful.
Use a tuple when: You need an immutable, hashable container — for example, as a dictionary key or function return value that should not change after creation.
Practical Example: Finding Unique Words in a Text
Here is a real-world use case: extracting all unique words from a document to count how many distinct terms appear — useful for building a vocabulary index or detecting duplicate entries in a log.
def unique_words(text):
"""Return the set of unique words in a text string."""
words = text.lower().split()
return set(words)
description = """
Python sets are powerful. Sets let you remove duplicates automatically.
Python also has powerful list and dictionary types.
"""
unique = unique_words(description)
print(f"Unique words: {sorted(unique)}")
print(f"Count: {len(unique)}")
# Output:
# Unique words: ['also', 'and', 'are', 'automatically.', 'dictionary', 'duplicates', 'has', 'let', 'list', 'powerful', 'powerful.', 'python', 'remove', 'sets', 'types.', 'you']
# Count: 16
Common Mistakes / Gotchas
- Putting mutable objects in a set — Lists and dicts are not hashable. Attempting
{{1, [2, 3]}}raisesTypeError: unhashable type: 'list'. Use tuples instead:{1, (2, 3)}works because tuples are immutable and hashable. - Confusing
{}with an empty set —{}creates a dict. Always useset()for an empty set. - Sets are unordered — You cannot rely on element order. If order matters, use a list. Sets make no guarantees about iteration order — not even insertion order.
- Modifying a set while iterating — This raises a
RuntimeError. Iterate over a copy:for item in set(some_set): - Assuming stable order across Python versions — Set iteration order is deterministic within a single run but is not guaranteed to match insertion order, and may differ between Python versions. Do not depend on it.
Summary & Next Steps
Python sets are an unordered, mutable collection of unique, hashable elements. Their hash-table implementation gives you O(1) membership testing — a massive speedup over the O(n) scans required by lists. Sets excel at deduplication, membership tests, and mathematical set operations like union and intersection.
Now that you understand sets, you are ready to explore related topics:
- Python Lists for Beginners — ordered, mutable sequences with index access
- Python Learning Path — structured guide from beginner to advanced
- Introduction to Python Programming — foundations for absolute beginners
- Official Python documentation on sets
- Python set types reference (docs.python.org)
- PEP 8 — Style Guide for Python Code
Frequently Asked Questions
How do you check if an element is in a Python set?
Use the in operator: "apple" in fruits. This runs in O(1) time because sets use a hash table internally. For lists, the same check would take O(n) time — sets are significantly faster for large collections. See the official Python documentation on set types for details.
What is the difference between remove() and discard() in Python sets?
remove() deletes an element and raises KeyError if the element does not exist. discard() also deletes the element but silently does nothing if it is missing — no error is raised. Use discard() when you are not sure whether the element is present, and remove() when its absence should signal a bug.
Can a Python set contain lists or dictionaries?
No. Sets require their elements to be hashable (immutable). Lists and dictionaries are mutable and therefore cannot be placed inside a set. Use tuples instead — {(1, 2), (3, 4)} is valid because tuples are immutable. If you need an immutable set, use frozenset.
What is the time complexity of set operations in Python?
Membership tests (in), adding, and removing elements are all O(1) on average. Set operations like union(), intersection(), and difference() are O(len(s) + len(t)). These are amortized averages — worst case can degrade to O(n), but it is rare in practice. See the Python docs on set types for the full complexity table.

