Python Sets: Complete Master Notes & Practice Solutions
Master Python Sets from fundamental characteristics, duplicate elimination, set methods, mathematical set operations (union, intersection, difference, symmetric difference) to real-world applications and step-by-step practice solutions.
1. What is a Set in Python?
English Definition
A Set is an unordered, unindexed collection of unique elements in Python. Sets do not allow duplicate values and are defined using curly brackets {} or the set() constructor.
Hinglish Explanation
Set Python mein ek aisa data structure hai jisme unique values store hoti hain. Jab hum set banate hain to duplicate values automatically remove ho jaati hain aur iska element order fixed nahi hota.
- Unordered: Elements have no defined order and may appear in different order when printed.
- Unique Elements: Duplicate entries are automatically discarded upon creation.
- Unindexed: Elements cannot be accessed using index numbers like
set[0]. - Mutable Set Container: We can add or remove elements after creation.
2. Creating a Set & Automatic Duplicate Removal
Sets are created using curly brackets {}. Notice how duplicate numbers like 20 and 40 are automatically filtered out when printed.
numbers = {10, 20, 30, 40, 50, 40, 20, "gagan", -944, 2.5}
print("Set Output:", numbers)
3. Sets Cannot Use Indexing
Why Indexing Fails
Since sets are unordered collections without positional indices, attempting to access elements via square brackets numbers[0] will raise a TypeError.
Hinglish Explanation
Sets unordered hote hain, isliye inme indexing kaam nahi karti. numbers[0] likhne par Python error dega.
numbers = {10, 20, 30}
try:
print(numbers[0])
except TypeError as e:
print("Error:", e)
4. Traversing (Looping) & Length of a Set
Even though sets cannot be indexed, you can easily iterate over set items using a for loop or count elements using len().
numbers = {10, 20, 30, 40}
print("Total elements (len):", len(numbers))
print("Iterating over set elements:")
for item in numbers:
print(item)
Iterating over set elements:
40
10
20
30
5. Adding Elements (add vs update)
| Method | Syntax | Description |
|---|---|---|
| add() | set.add(element) |
Adds a single element to the set. |
| update() | set.update(iterable) |
Adds multiple elements from a list, tuple, or another set. |
numbers = {10, 20}
numbers.add(30)
print("After add(30):", numbers)
numbers.update([40, 50, 60])
print("After update([40, 50, 60]):", numbers)
After update([40, 50, 60]): {40, 10, 50, 20, 60, 30}
6. Removing Elements (remove, discard, pop, clear)
remove() vs discard() Critical Difference
remove(x): Deletes x. Raises a KeyError if x is not present in the set.
discard(x): Deletes x. Does NOT raise any error if x is missing.
Hinglish Explanation
remove() error deta hai agar value set mein na mile. Jabki discard() safe method hai, element na milne par silently skip ho jata hai bina error diye.
numbers = {10, 20, 30, 40, 50}
numbers.remove(20)
print("After remove(20):", numbers)
numbers.discard(100)
print("After discard(100) [No error]:", numbers)
popped_item = numbers.pop()
print("Popped random element:", popped_item)
print("After pop():", numbers)
numbers.clear()
print("After clear():", numbers)
After discard(100) [No error]: {40, 10, 50, 30}
Popped random element: 40
After pop(): {10, 50, 30}
After clear(): set()
7. Mathematical Set Operations
| Operation | Operator | Method | Description |
|---|---|---|---|
| Union | a | b |
a.union(b) |
Combines elements from both sets (no duplicates). |
| Intersection | a & b |
a.intersection(b) |
Extracts only common elements present in both sets. |
| Difference | a - b |
a.difference(b) |
Elements in a that are not in b. |
| Symmetric Difference | a ^ b |
a.symmetric_difference(b) |
Elements in either set, but not in both (removes common). |
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print("Union (a | b):", a | b)
print("Intersection (a & b):", a & b)
print("Difference (a - b):", a - b)
print("Symmetric Difference (a ^ b):", a ^ b)
Intersection (a & b): {3, 4}
Difference (a - b): {1, 2}
Symmetric Difference (a ^ b): {1, 2, 5, 6}
8. Important Set Methods Summary
| Method | Action / Usage |
|---|---|
add(val) |
Adds a single element to the set. |
update(seq) |
Adds multiple elements from any iterable. |
remove(val) |
Deletes element (raises KeyError if missing). |
discard(val) |
Deletes element without throwing an error if missing. |
pop() |
Removes and returns an arbitrary random element. |
clear() |
Removes all items, leaving an empty set set(). |
union() |
Returns a new set with all items from both sets. |
intersection() |
Returns a new set with common elements. |
difference() |
Returns elements present in first set only. |
symmetric_difference() |
Returns non-overlapping elements from both sets. |
9. Real-Life Applications of Python Sets
- 1. Duplicate Removal: Easily converting lists with duplicates into sets (e.g.
list(set(raw_data))). - 2. Fast Membership Testing: Checking if an item exists in O(1) time complexity compared to O(n) in lists.
- 3. Mathematical Data Operations: Finding common followers, mutual friends, shared interests across datasets.
- 4. Data Comparison & Filtering: Comparing differences between two database tables or log files.
10. Set Practice Questions List
1. Create a set with 5 numbers and print it.
2. Add an element to a set using add().
3. Add multiple elements to a set using update().
4. Remove an element from a set using remove().
5. Remove an element safely using discard().
6. Print the total count of elements using len().
7. Print all elements using a for loop.
8. Find the union of two sets using union().
9. Find the intersection of two sets using intersection().
10. Find the difference of two sets using difference().
11. Find the symmetric difference of two sets using symmetric_difference().
11. Step-by-Step Python Code Solutions
numbers = {10, 20, 30, 40, 50}
print("1. Set:", numbers)
s2 = {10, 20, 30}
s2.add(40)
print("2. After add(40):", s2)
s3 = {10, 20}
s3.update([30, 40, 50])
print("3. After update([30, 40, 50]):", s3)
s4 = {10, 20, 30}
s4.remove(20)
print("4. After remove(20):", s4)
s5 = {10, 20, 30, 40}
print("5. Length:", len(s5))
s6 = {10, 20, 30}
print("6. Loop Items:")
for item in s6:
print(" -", item)
a = {1, 2, 3}
b = {3, 4, 5}
print("7. Union:", a.union(b))
a = {1, 2, 3}
b = {2, 3, 4}
print("8. Intersection:", a.intersection(b))
a = {1, 2, 3}
b = {2, 3, 4}
print("9. Difference (a - b):", a.difference(b))
a = {1, 2, 3}
b = {3, 4, 5}
print("10. Symmetric Difference:", a.symmetric_difference(b))
2. After add(40): {40, 10, 20, 30}
3. After update([30, 40, 50]): {40, 10, 50, 20, 30}
4. After remove(20): {10, 30}
5. Length: 4
6. Loop Items:
- 10
- 20
- 30
7. Union: {1, 2, 3, 4, 5}
8. Intersection: {2, 3}
9. Difference (a - b): {1}
10. Symmetric Difference: {1, 2, 4, 5}