In Python, a set is a built-in data structure that stores unordered, unique elements. Sets are incredibly useful when you need to eliminate duplicates, perform mathematical set operations, or check for membership efficiently.
Let’s explore how sets work and how you can use them in your Python programs.
A set is defined using curly braces {} or the set() constructor.
# Using curly braces
fruits = {"apple", "banana", "cherry"}
# Using set() constructor
numbers = set([1, 2, 3, 4])
⚠️ Note: You cannot create an empty set using {} — that creates an empty dictionary. Use set() instead.
Unordered: The elements have no fixed position.
Unique: Duplicate elements are automatically removed.
Mutable: You can add or remove elements.
Iterable: You can loop through a set.
data = {1, 2, 2, 3, 4}
print(data) # Output: {1, 2, 3, 4}
Here are some useful methods to manipulate sets:
add(elem) - Adds an element
remove(elem) - Removes an element (raises error if not found)
discard(elem) - Removes an element (no error if not found)
pop() - Removes and returns a random element
clear() - Removes all elements
len(set) - Returns the number of elements
colors = {"red", "green"}
colors.add("blue")
colors.discard("green")
print(colors) # Output: {'red', 'blue'}
Python supports standard set theory operations:
Combines elements from both sets.
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # {1, 2, 3, 4, 5}
print(a.union(b)) # {1, 2, 3, 4, 5}
Returns common elements.
print(a & b) # {3}
print(a.intersection(b)) # {3}
Returns elements in a but not in b.
print(a - b) # {1, 2}
print(a.difference(b)) # {1, 2}
Returns elements in either set, but not both.
print(a ^ b) # {1, 2, 4, 5}
Sets are optimized for fast membership checks.
print(2 in a) # True
print(5 not in a) # True
Removing duplicates from a list
Fast membership testing
Performing mathematical set operations
Representing unique items (e.g., tags, categories)
Try this:
# Remove duplicates from a list
names = ["Ali", "Sara", "Ali", "Zara", "Sara"]
unique_names = set(names)
print(unique_names)
Sets are a powerful and efficient way to handle collections of unique items in Python. Whether you're cleaning data or performing mathematical operations, sets make your code cleaner and faster.
Next Up: Dictionaries and key-value access