Sets are used to store multiple items in a single variable. A set is a collection which is unordered, unchangeable, and unindexed.
Sets are written with curly brackets {}.
- Unordered: The items do not have a defined order. You cannot be sure in which order the items will appear!
- Unchangeable (Items): Once a set is created, you cannot change its items, but you can add new items or remove them.
- Unindexed: You cannot access items in a set by referring to an index or a key.
- No Duplicates Allowed: Sets cannot have two items with the same value. Duplicates will be silently ignored!
Tip
Real-World Examples:
- Unique User IDs (Deduplication): If you are tracking the IP addresses of visitors to a website, you will likely get thousands of identical entries from the same person refreshing the page. By storing the IPs in a Set, Python automatically enforces the No Duplicates rule and instantly discards any repeating IPs, leaving you with a perfectly clean list of unique visitors. The exact sequence of these IPs is irrelevant, which is why Sets are completely unordered and unindexed.
- Tagging Systems: Imagine finding articles that are tagged with both "Python" and "Data Science". Because sets are mathematically modeled, you can perform a lightning-fast
Intersectionoperation on two sets of tags to instantly return the overlap. The order of the tags doesn't matter (they are unordered), and you can't accidentally add the "Python" tag to an article twice (it enforces No Duplicates), making it the perfect, lightweight data structure for categorization.
Input:
# Creating a set with duplicates
thisset = {"apple", "banana", "cherry", "apple"}
# Notice how 'apple' only appears once!
print(thisset)
print("Length:", len(thisset))
# Notice that True and 1 are considered the same value in sets!
# 0 and False are also considered the same value.
set2 = {"apple", "banana", "cherry", True, 1, 2}
print(set2)Output:
{'banana', 'apple', 'cherry'}
Length: 3
{'banana', 'apple', 'cherry', True, 2}
(Note: Because sets are unordered, the output order may be different every time you run the code!)
When initializing an empty set, you must use the constructor function set().
If you use empty curly braces {}, Python will initialize an empty dictionary instead of a set.
Input:
# Correct way to create an empty set
empty_set = set()
print("set() type:", type(empty_set))
# Using curly braces creates a dictionary!
empty_dict = {}
print("{} type :", type(empty_dict))Output:
set() type: <class 'set'>
{} type : <class 'dict'>
Because you cannot change items, you can only add or remove them.
.add(item): Adds a single item..update(iterable): Adds items from another set (or any iterable like a list/tuple) into the current set.
Input:
thisset = {"apple", "banana"}
# Add one item
thisset.add("orange")
print("After add:", thisset)
# Update with a list of items
tropical_list = ["mango", "papaya"]
thisset.update(tropical_list)
print("After update:", thisset)Output:
After add: {'orange', 'banana', 'apple'}
After update: {'orange', 'papaya', 'banana', 'apple', 'mango'}
.remove(item): Removes the item. If it doesn't exist, it throws an ERROR..discard(item): Removes the item. If it doesn't exist, it does NOTHING..pop(): Removes a random item (because sets are unordered, you don't know what will pop!).
Input:
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
thisset.discard("strawberry") # Does not throw an error!
popped_item = thisset.pop() # Removes a random item
print("After removals:", thisset)
print("Item popped:", popped_item)Output:
After removals: {'cherry'}
Item popped: apple
Because Sets in Python are based on mathematical sets, they have incredibly powerful built-in methods for Venn-diagram style logic!
Returns a new set containing ALL items from both sets, excluding duplicates.
Input:
set1 = {"a", "b", "c"}
set2 = {1, 2, 3, "c"}
set3 = set1.union(set2)
print("Union:", set3)Output:
Union: {1, 2, 3, 'c', 'b', 'a'}
There is an important difference in Python between set methods and set operators when handling different data types:
- Set Operator (
|): Requires both operands to be set objects. Using a list, tuple, or dictionary will raise aTypeError. - Set Method (
.union()): Accepts any iterable as an argument (lists, tuples, dicts). Python automatically converts it to a set before joining.
Input:
set_a = {"apple", "banana"}
list_b = ["cherry", "date"]
# 1. Using set method works with lists!
union_method = set_a.union(list_b)
print("Union via method :", union_method)
# 2. Using set operator fails with lists!
try:
union_operator = set_a | list_b
except TypeError as e:
print("Union via operator:", e)Output:
Union via method : {'cherry', 'banana', 'date', 'apple'}
Union via operator: unsupported operand type(s) for |: 'set' and 'list'
Returns a new set containing ONLY the items that are present in BOTH sets (the overlap).
Input:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.intersection(y)
print("Intersection:", z)Output:
Intersection: {'apple'}
Returns a new set containing items that only exist in the first set, and NOT in the second set.
Input:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.difference(y)
print("Difference:", z)Output:
Difference: {'banana', 'cherry'}
You can quickly check the truthfulness of the items inside the set.
all()returnsTrueif all items in the set are true.any()returnsTrueif any item in the set is true.
Input:
my_set = {False, 0, ""}
my_set_two = {False, 0, "Hello"}
print("Are any true in set 1?", any(my_set))
print("Are any true in set 2?", any(my_set_two))Output:
Are any true in set 1? False
Are any true in set 2? True