⬅ Previous TopicPython Tuples
Next Topic ⮕Python Functions










Python Sets
A Set in Python is a collection of items where:
- Each item is unique (no duplicates allowed)
- The items are unordered (they don’t stay in the order you added them)
What Does a Set Look Like?
You can create a set using curly braces {}
or the set()
function.
fruits = {"apple", "banana", "orange"}
print(fruits)
{'banana', 'orange', 'apple'}
Note: The order might look different when you run it. That’s okay — sets are unordered, so the order is not fixed.
Why Use Sets?
- To store only unique values
- To remove duplicates from a list
- To quickly check if an item exists (sets are fast for lookups)
Removing Duplicates Example
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = set(numbers)
print(unique_numbers)
{1, 2, 3, 4, 5}
Why? Because sets automatically remove duplicates!
Basic Set Operations (CRUD)
Let’s learn the basic operations on sets: Create, Read, Update, and Delete.
1. Create a Set
colors = {"red", "green", "blue"}
2. Read Items
You can’t read by position, but you can check if something exists:
colors = {"red", "green", "blue"}
print("green" in colors) # True
print("yellow" in colors) # False
3. Add Items
colors = {"red", "green", "blue"}
colors.add("yellow")
print(colors)
{'red', 'green', 'blue', 'yellow'}
4. Remove Items
You can use remove()
or discard()
:
colors = {"red", "green", "blue"}
colors.remove("green") # Removes green
colors.discard("pink") # Does nothing (pink not found)
print(colors)
{'red', 'blue', 'yellow'}
5. Clear All Items
colors = {"red", "green", "blue"}
colors.clear()
print(colors)
set()
This means the set is now empty.
Conclusion
Sets are perfect when you want to keep only unique items and don’t care about the order. They are simple, fast, and super useful when removing duplicates or checking membership.