π Python Sets β Create, Modify, and Use Set Operations
π§² Introduction β What Is a Set in Python?
A set in Python is an unordered, unindexed collection that stores only unique elements. Itβs ideal for deduplication, fast membership tests, and performing set-theory operations like union, intersection, and difference.
Unlike lists or tuples, sets are mutable (can be changed) but do not allow duplicates or maintain order.
π― In this guide, youβll learn:
- How to create, access, and modify Python sets
- Core set operations like union and intersection
- Methods for copying, joining, and updating sets
- Real-world applications with exercises
π Topics Covered
π§© Topic | π Description |
---|---|
Python Sets: Access / Add / Remove | Creating sets, adding/removing elements, and accessing items |
Python Loop Sets | Iterating through sets |
Python Copy / Join Sets | Duplicating and combining sets |
Python Set Operators | Union, intersection, difference, symmetric difference |
Python Set Methods | Built-in methods for set manipulation |
Python Set Exercises | Practice problems to test understanding |
π§° Creating Sets in Python
fruits = {"apple", "banana", "cherry"}
print(fruits)
β Explanation:
- Sets use
{}
or theset()
constructor. - Duplicates are automatically removed.
πΉ Using set()
Constructor
numbers = set([1, 2, 3, 2])
print(numbers) # Output: {1, 2, 3}
β Converts any iterable (like list/tuple) into a set.
π Accessing and Looping Through Sets
πΉ Loop through elements:
for fruit in fruits:
print(fruit)
β Sets are unordered, so the order may change with every execution.
π§ͺ Adding and Removing Elements
β
add()
β Add a single item:
fruits.add("orange")
β
update()
β Add multiple items:
fruits.update(["grape", "melon"])
β
remove()
β Remove item, raises error if not found:
fruits.remove("banana")
β
discard()
β Remove item safely:
fruits.discard("kiwi")
π Set Operations β Algebraic Power
β
Union (|
or .union()
)
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # {1, 2, 3, 4, 5}
β
Intersection (&
or .intersection()
)
print(a & b) # {3}
β
Difference (-
or .difference()
)
print(a - b) # {1, 2}
β
Symmetric Difference (^
or .symmetric_difference()
)
print(a ^ b) # {1, 2, 4, 5}
π Set Methods Summary
Method | Description |
---|---|
add() | Add one item |
update() | Add multiple items |
remove() | Remove item (error if not found) |
discard() | Remove item (no error if not found) |
pop() | Remove a random item |
clear() | Empty the set |
union() | Combine two sets |
intersection() | Common elements |
difference() | Elements in one set but not the other |
symmetric_difference() | Elements in either set but not both |
π§ Best Practices
β
Use set()
to remove duplicates from lists/tuples.
β
Use discard()
instead of remove()
to avoid runtime errors.
β
Leverage set math for clean filtering and comparison.
β
Convert data from files/inputs to sets for faster lookups.
π§ͺ Python Set Exercises
πΉ 1. Remove Duplicates from a List
nums = [1, 2, 2, 3, 4, 4]
unique = list(set(nums))
print(unique)
πΉ 2. Find Common Items Between Two Sets
a = {"a", "b", "c"}
b = {"b", "c", "d"}
print(a & b)
πΉ 3. Combine Two Sets and Remove Duplicates
x = {1, 2}
y = {2, 3}
print(x | y)
πΉ 4. Filter Items Not in Both Sets
x = {1, 2, 3}
y = {3, 4, 5}
print(x ^ y)
πΉ 5. Safely Remove an Element
items = {"pen", "pencil", "eraser"}
items.discard("marker") # no error
print(items)
π Summary β Recap & Next Steps
Python sets offer unmatched performance for deduplication, fast lookups, and set-theoretic logic. With support for union, intersection, and difference operations, sets are a powerful tool for solving many programming challenges efficiently.
π Key Takeaways:
- Sets store unique, unordered elements.
- Use
.add()
,.update()
,.remove()
,.discard()
to manage items. - Perform set math using operators:
|
,&
,-
,^
. - Use sets to filter data and validate membership.
βοΈ Real-World Relevance:
Sets are used in data science, validation checks, permission systems, and duplicate removal in large datasets.
β FAQ Section β Python Sets
β What is a set in Python?
β
A set is an unordered collection of unique items. Defined with {}
or set()
.
β Can sets contain duplicates?
β
No. Any repeated values are automatically removed.
β Whatβs the difference between remove()
and discard()
?
β
remove()
raises an error if the item doesn’t exist; discard()
does not.
β How to remove duplicates from a list using sets?
β
Convert it:
list(set([1, 2, 2, 3])) # Output: [1, 2, 3]
β Are sets mutable?
β
Yes. You can add/remove elements. For immutability, use frozenset
.
Share Now :