Python - Set
1. What is a Set in Python?
A Set is a built-in data type in Python that stores multiple items. It is unordered, does not allow duplicate values, and is mutable.
It works similar to a mathematical set.
my_set = {1, 2, 3, 4}
print(my_set)
Output:
{1, 2, 3, 4}
2. Important Properties of Set
- Unordered
- No Duplicates
- Mutable
- No Indexing
numbers = {1, 2, 2, 3, 4, 4}
print(numbers)
Output:
{1, 2, 3, 4}
3. Creating a Set
Method 1: Using Curly Braces
fruits = {"apple", "banana", "mango"}
print(fruits)
Method 2: Using set() Constructor
numbers = set([1, 2, 3, 4]) print(numbers)
Important: {} creates a dictionary, not a set.
empty_set = set()
4. Accessing Set Elements
Sets are unordered, so indexing is not allowed.
my_set[0] # Error
You can loop through elements.
colors = {"red", "green", "blue"}
for color in colors:
print(color)
5. Adding Elements
add() adds a single element.
numbers = {1, 2, 3}
numbers.add(4)
print(numbers)
update() adds multiple elements.
numbers = {1, 2}
numbers.update([3, 4, 5])
print(numbers)
6. Removing Elements
remove() removes element and gives error if not found.
numbers = {1, 2, 3}
numbers.remove(2)
print(numbers)
discard() does not give error if element not found.
numbers = {1, 2, 3}
numbers.discard(5)
print(numbers)
pop() removes random element.
numbers = {1, 2, 3}
numbers.pop()
print(numbers)
clear() removes all elements.
numbers = {1, 2, 3}
numbers.clear()
print(numbers)
7. Set Operations
Union combines two sets.
A = {1, 2, 3}
B = {3, 4, 5}
print(A | B)
print(A.union(B))
Intersection finds common elements.
print(A & B) print(A.intersection(B))
Difference finds elements in A but not in B.
print(A - B) print(A.difference(B))
Symmetric Difference finds non-common elements.
print(A ^ B) print(A.symmetric_difference(B))
8. Set Comparison Methods
A = {1, 2}
B = {1, 2, 3}
print(A.issubset(B))
print(B.issuperset(A))
print(A.isdisjoint({4, 5}))
9. Frozen Set
A frozenset is an immutable version of set. It cannot be modified.
fs = frozenset([1, 2, 3]) print(fs) fs.add(4) # Error
10. When to Use Set?
- Remove duplicates
- Fast membership checking
- Perform mathematical operations
- Order is not important
11. Practical Real Example
Removing duplicate students from list.
students = ["Ravi", "Amit", "Ravi", "Sita", "Amit"] unique_students = set(students) print(unique_students)
12. Important Built-in Functions
numbers = {1, 2, 3, 4}
print(len(numbers))
print(max(numbers))
print(min(numbers))
print(sum(numbers))
Final Summary
- Set = Unordered + No duplicates
- No indexing
- Supports mathematical operations
- Mutable (except frozenset)
- Very fast for membership checking