A set is a built-in Python data structure that is:
Unordered: No guaranteed order of elements
Unindexed: No indexing or slicing
Mutable: You can add/remove elements
No Duplicates: Automatically removes duplicate values
✅ Think of a set as a collection of unique items, like a bag of distinct balls.
my_set = {1, 2, 3, 4}
print(my_set) # Output: {1, 2, 3, 4}
# OR using the set() constructor
new_set = set([1, 2, 2, 3])
print(new_set) # Output: {1, 2, 3}
❌ You cannot create an empty set using
{}
→ this creates a dictionary.
Useset()
instead.
Property | Description |
---|---|
Unordered | Elements have no fixed position |
Unique | No duplicate values allowed |
Mutable | Can add or remove elements |
Iterable | Can loop through it |
for item in my_set:
print(item)
❌ No indexing like
my_set[0]
— it will raise an error.
my_set.add(5) # Add one item
my_set.update([6, 7]) # Add multiple items
my_set.remove(2) # Remove item (raises error if not found)
my_set.discard(10) # Remove item (no error if not found)
my_set.pop() # Remove and return random item
my_set.clear() # Remove all items
A = {1, 2, 3}
B = {3, 4, 5}
print(A | B) # Union: {1, 2, 3, 4, 5}
print(A & B) # Intersection: {3}
print(A - B) # Difference: {1, 2}
print(A ^ B) # Symmetric Difference: {1, 2, 4, 5}
A = {1, 2}
B = {1, 2, 3}
print(A.issubset(B)) # True
print(B.issuperset(A)) # True
print(A.isdisjoint({4})) # True (no common elements)
Feature | List | Set |
---|---|---|
Ordered | Yes | No |
Duplicates | Allowed | Not allowed |
Indexing | Yes | No |
Performance | Slower lookups | Faster (hashed) |
A set is like a guest list at a private event:
You can’t invite the same person twice.
You don’t care about the order of arrival.
You just want to know who’s coming.
Sets store unique, unordered values.
Great for membership tests, removing duplicates, and set operations.
Use add()
, remove()
, and update()
for modifications.