Python Sets
🐍 Python Sets — Complete Tutorial
A set in Python is a collection of unordered, mutable, and unique items.
✔ Key Characteristics of Sets
| Feature | Description |
|---|---|
| Unordered | Items do not have a fixed position (no indexing) |
| Mutable | You can add or remove items |
| Unique items | No duplicate values are allowed |
| Iterable | You can loop through sets |
🔹 Creating a Set
If you create an empty set, you must use set(), because {} creates a dictionary.
🔹 Set Removes Duplicate Values
🔹 Accessing Set Items
Since sets are unordered, you cannot use indexing, but you can loop:
🔹 Adding Items to a Set
➤ add() — Add a single element
➤ update() — Add multiple elements
🔹 Removing Items from a Set
| Method | Behavior |
|---|---|
remove() |
Removes an element; error if not found |
discard() |
Removes element; no error if not found |
pop() |
Removes a random element |
clear() |
Removes all elements |
Examples:
🔹 Set Operations (Important)
Python sets support mathematical set operations.
1️⃣ Union (| or union())
2️⃣ Intersection (& or intersection())
3️⃣ Difference (- or difference())
4️⃣ Symmetric Difference (^ or symmetric_difference())
🔹 Check Membership
🔹 Copying a Set
🔹 Frozen Set (Immutable Set)
A frozenset is unchangeable.
🏆 Summary Table
| Operation | Method |
|---|---|
| Add element | add() |
| Add multiple values | update() |
| Remove with error | remove() |
| Remove without error | discard() |
| Remove random item | pop() |
| Union | union() or ` |
| Intersection | intersection() or & |
| Difference | difference() or - |
| Symmetric Difference | symmetric_difference() or ^ |
🧠 Practice Exercises
Try these now:
-
Create a set with values:
10, 20, 30, 40, 50.
Add60and remove20. -
Given:
Find:
-
Union
-
Intersection
-
Difference
-
Symmetric Difference
-
Convert this list to a set and remove duplicates:
