Python Sets
A set in Python is a built-in data type that allows you to store unordered, unique elements. Sets are especially useful when you need to eliminate duplicates or perform mathematical set operations like union, intersection, and difference.
Creating a Set
You can create a set by using curly braces {}
or the set()
function.
# Using curly braces
fruits = {"apple", "banana", "cherry"}
# Using the set() constructor
numbers = set([1, 2, 3, 3, 2])
print(numbers)
Output:
{1, 2, 3}
- Sets automatically remove duplicates.
- The elements have no defined order.
Key Characteristics of Sets
- Unordered: The items do not have an index and their order can change.
- Unchangeable (immutable) items: The items inside must be hashable (e.g., no lists or dictionaries).
- No duplicates: Any duplicate item is removed automatically.
Accessing Items in a Set
You can't access set items using an index. But you can iterate through them using a for
loop.
colors = {"red", "green", "blue"}
for color in colors:
print(color)
Output:
red
green
blue
(Note: The order may vary.)
Adding Items to a Set
Use add()
to add a single item and update()
to add multiple items.
animals = {"cat", "dog"}
animals.add("rabbit")
print(animals)
animals.update(["horse", "cow"])
print(animals)
Output:
{'cat', 'dog', 'rabbit'}
{'cat', 'dog', 'rabbit', 'horse', 'cow'}
Removing Items from a Set
There are several ways to remove items from a set:
remove(item)
: Removes the item, but raises an error if it doesn't exist.discard(item)
: Removes the item, does nothing if the item is missing.pop()
: Removes and returns a random item.clear()
: Empties the set.
my_set = {"a", "b", "c"}
my_set.remove("b")
print(my_set)
my_set.discard("x") # No error
print(my_set)
item = my_set.pop()
print(f"Popped item: {item}")
print(my_set)
my_set.clear()
print(my_set)
Output:
{'a', 'c'}
{'a', 'c'}
Popped item: a
{'c'}
set()
Set Operations
Python sets support powerful operations that mirror mathematical set theory.
Union
Combines all unique elements from both sets.
a = {1, 2, 3}
b = {3, 4, 5}
print(a.union(b)) # or a | b
Output:
{1, 2, 3, 4, 5}
Intersection
Finds elements common to both sets.
print(a.intersection(b)) # or a & b
Output:
{3}
Difference
Elements that are in a
but not in b
.
print(a.difference(b)) # or a - b
Output:
{1, 2}
Symmetric Difference
Elements that are in either set, but not in both.
print(a.symmetric_difference(b)) # or a ^ b
Output:
{1, 2, 4, 5}
Set Comparisons
You can check relationships between sets using:
issubset()
: Check if all elements of one set are in another.issuperset()
: Check if a set contains all elements of another.isdisjoint()
: Check if two sets have no elements in common.
x = {1, 2}
y = {1, 2, 3}
print(x.issubset(y)) # True
print(y.issuperset(x)) # True
print(x.isdisjoint({3})) # True
Sets vs Lists: When to Use Sets
-
Use sets when:
- You need uniqueness.
- You want fast membership testing (
in
operator). - You need to perform set operations.
-
Use lists when:
- You need ordered elements.
- Duplicates are allowed.
- You need to index items.
Summary
- Sets are unordered collections of unique and immutable items.
- Use
add()
,remove()
,union()
,intersection()
, etc., to manage and compare sets. - Sets are ideal for tasks involving uniqueness and membership testing.
- Unlike lists, sets don’t maintain order or allow duplicates.
Understanding sets helps you write cleaner, more efficient Python code, especially when dealing with collections of distinct items.
Continue Learning
Python Variables
Popular
### Understanding Variables and Literals in Python Variables and literals are the foundation of any
Personalized Recommendations
Log in to get more relevant recommendations based on your reading history.