A set in Python is an unordered collection of unique items. Sets are useful when you want to remove duplicates, check membership quickly, or perform mathematical set operations such as union, intersection, difference, and symmetric difference.
Tested on: Python 3.13.3; kernel 6.14.0-37-generic.
Python set quick reference
| Task | Use |
|---|---|
| Create a set | my_set = {1, 2, 3} |
| Create an empty set | my_set = set() |
| Convert list to set | set(my_list) |
| Add one item | my_set.add(item) |
| Add multiple items | my_set.update(items) |
| Check membership | item in my_set |
| Remove item and raise error if missing | my_set.remove(item) |
| Remove item safely | my_set.discard(item) |
| Remove arbitrary item | my_set.pop() |
| Remove all items | my_set.clear() |
| Union | a | b or a.union(b) |
| Intersection | a & b or a.intersection(b) |
| Difference | a - b or a.difference(b) |
| Symmetric difference | a ^ b or a.symmetric_difference(b) |
| Check subset | a.issubset(b) or a <= b |
| Check superset | a.issuperset(b) or a >= b |
What is a set in Python?
- A set is a collection of unique items.
- It is unordered—display order is not guaranteed.
- It is mutable—you can add and remove items.
- It can contain only hashable items (no lists or dicts as elements).
- Duplicate values are removed automatically.
- You cannot access set items by index.
Sets are useful for uniqueness, membership testing, and set operations. See list vs set vs tuple vs dictionary for a broader comparison.
Create a set in Python
Non-empty set with curly braces:
tags = {"python", "set", "tutorial"}
print(tags)Empty set with set():
empty = set()
print(empty)
print(type(empty))Important: {} creates an empty dictionary, not an empty set.
Convert from other types:
numbers = set([1, 2, 2, 3, 3, 3])
letters = set("hello")
keys_only = set({"a": 1, "b": 2})
from_tuple = set((1, 2, 3))
print(numbers)
print(letters)
print(keys_only)
print(from_tuple)numbers becomes {1, 2, 3}. A string becomes individual characters. A dictionary conversion uses keys only.
Python set example
Duplicates are removed and order is not fixed:
colors = {"red", "blue", "green", "red", "blue"}
print(colors)
print(len(colors))
scores = [10, 20, 20, 30, 10]
unique_scores = set(scores)
print(unique_scores)You see three unique colors and three unique scores; the printed order may vary between runs.
Add items to a Python set
One item with add():
fruits = {"apple", "mango"}
fruits.add("grape")
fruits.add("apple")
print(fruits)"apple" is not duplicated.
Multiple items with update():
fruits = {"apple", "mango"}
fruits.update(["grape", "banana"])
fruits.update({"kiwi", "apple"})
print(fruits)update() accepts lists, tuples, strings, or another set.
Access or loop through set items
Sets are iterable, but not indexable:
tags = {"python", "set", "data"}
for tag in tags:
print(tag)Use in to test membership—you cannot use tags[0].
Check if an item exists in a set
allowed = {"admin", "editor", "viewer"}
selected = {"python", "set", "tutorial"}
print("admin" in allowed)
print("guest" in allowed)
print("python" in selected)
print("java" in selected)Membership checks are one of the main reasons to use sets—for usernames, tags, or allowed IDs.
Remove items from a Python set
| Method | Missing item behavior |
|---|---|
remove() |
Raises KeyError |
discard() |
No error |
pop() |
Raises KeyError only if set is empty |
clear() |
Removes all items |
items = {"ab", "dc", "cd"}
items.discard("missing")
print(items)
items.remove("dc")
print(items)
removed = items.pop()
print(removed)
print(items)
items.clear()
print(items)pop() removes an arbitrary item—not the “first” item, because sets are unordered.
items = {"x", "y"}
try:
items.remove("z")
except KeyError as e:
print(e)remove("z") raises KeyError.
Python set operations
| Operation | Meaning | Method | Operator |
|---|---|---|---|
| Union | Items in either set | a.union(b) |
a | b |
| Intersection | Items in both sets | a.intersection(b) |
a & b |
| Difference | Items in a but not b |
a.difference(b) |
a - b |
| Symmetric difference | Items in either set, but not both | a.symmetric_difference(b) |
a ^ b |
Python's set documentation lists these methods and operator forms for set and frozenset.
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print(A | B)
print(A & B)
print(A - B)
print(B - A)
print(A ^ B)Python set union
Union combines unique items from both sets and returns a new set:
tags_a = {"python", "linux", "cloud"}
tags_b = {"python", "docker", "cloud"}
combined = tags_a.union(tags_b)
print(combined)
print(tags_a | tags_b)Use union to merge categories, IDs, or tags without duplicates.
Python set intersection
Intersection returns only common items. For method details and operator forms, see Python set intersection.
group_a = {101, 102, 103, 104}
group_b = {103, 104, 105, 106}
shared = group_a & group_b
print(shared)Output is {103, 104}—users or tags present in both collections.
Python set difference
Difference is one-sided—items in the first set that are not in the second:
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print(A - B)
print(B - A)You get {1, 2} and {5, 6}. A - B is not the same as B - A. See Python set difference for more examples.
Python set symmetric difference
Symmetric difference returns items in either set, but not both:
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print(A.symmetric_difference(B))
print(A ^ B)Both produce {1, 2, 5, 6}. For more detail, see Python symmetric difference.
Python issubset()
issubset() returns True when all items in one set are in another:
required = {"email", "password"}
submitted = {"email", "password", "remember_me"}
print(required.issubset(submitted))
print(submitted.issubset(required))
print(required <= submitted)The first and third checks are True; the second is False.
issubset() vs issuperset() vs isdisjoint()
| Method | Meaning |
|---|---|
a.issubset(b) |
All items in a are also in b |
a.issuperset(b) |
a contains all items of b |
a.isdisjoint(b) |
a and b have no common items |
a = {1, 2, 3}
b = {1, 2, 3, 4, 5}
c = {6, 7}
print(a.issubset(b))
print(b.issuperset(a))
print(a.isdisjoint(c))Results are True, True, and True.
Set vs list vs tuple vs dictionary
| Feature | Set | List | Tuple | Dictionary |
|---|---|---|---|---|
| Unique items | Yes | No | No | Keys are unique |
| Ordered | No | Yes | Yes | Yes (insertion order) |
| Mutable | Yes | Yes | No | Yes |
| Index access | No | Yes | Yes | Key-based |
| Main use | Unique items and set operations | Ordered changeable collection | Fixed ordered values | Key-value lookup |
Use a set when duplicates or fast membership matter more than order.
Frozenset in Python
frozenset is an immutable set:
frozen = frozenset([1, 2, 3, 2])
print(frozen)
lookup = {frozenset({"a", "b"}): "group-a"}
print(lookup[frozenset({"b", "a"})])You cannot add or remove items after creation. A frozenset can be a dictionary key or an element inside another set when all items are hashable.
When should you use a set?
- Remove duplicates from a list:
list(set(items))— lists keep order and duplicates; see Python list when those matter. - Check membership quickly with
in - Compare two collections for shared or unique values
- Track unique visitors, tags, or IDs
- Run union, intersection, difference, or symmetric difference
Avoid sets when you need duplicate values or a stable order.
Common mistakes with Python sets
- Using
{}for an empty set — it creates a dict; useset(). - Expecting fixed display order — sets are unordered.
- Indexing a set —
my_set[0]is invalid. - Adding lists or dicts as elements — only hashable items are allowed.
- Confusing
remove()anddiscard()— onlyremove()errors when missing. - Thinking
pop()removes the first item — it removes an arbitrary item. - Forgetting duplicates are removed —
{1, 1, 2}is{1, 2}. - Using sets when order or duplicates matter — use a list instead.
- Assuming set operations preserve list order — convert back with
sorted()if needed.
Summary
A Python set stores unique, unordered items. Use {} for non-empty sets and set() for an empty set. Modify sets with add(), update(), remove(), discard(), and clear(). Compare collections with union, intersection, difference, and symmetric difference. Check relationships with issubset(), issuperset(), and isdisjoint().
Useful references

