Sets in Python
A set is a collection of unique items. Sets are unordered and do not allow duplicates.
💡 Sets are written using curly brackets { }.
Creating a Set
numbers = {1, 2, 3, 4}
colors = {"red", "green", "blue"}
print(numbers)
print(colors)
No Duplicate Values
Duplicate values are automatically removed.
nums = {1, 2, 2, 3, 3, 4}
print(nums)
Adding & Removing Elements
fruits = {"apple", "banana"}
fruits.add("orange")
fruits.remove("banana")
print(fruits)
Set Operations
Sets support mathematical operations like union and intersection.
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # Union
print(a & b) # Intersection
print(a - b) # Difference
Checking Membership
langs = {"python", "java", "c++"}
print("python" in langs)
print("ruby" in langs)
When to Use Sets?
- To remove duplicates
- Fast membership testing
- Mathematical operations
Practice Exercises
- Create a set of five numbers
- Add two new numbers
- Remove one number
- Find intersection of two sets