Mastering Python Sets: Remove Duplicates and Do More
Mastering Python Sets: Remove Duplicates and Do More ๐งบ
set is a built-in data type in Python that stores unique items. It's ideal for eliminating duplicates and performing mathematical operations like union and intersection.
✅ Basic set usage
Check if a specific item exists in the set:
fruits = {"apple", "banana", "cherry"}
print("banana" in fruits) # True
✅ Set operations: union, intersection, difference
Sets support powerful operations for comparing multiple sets:
a = {1, 2, 3}
b = {3, 4, 5}
print(a.union(b)) # union
print(a.intersection(b)) # intersection
print(a.difference(b)) # difference
✅ Remove duplicates from a list
Convert a list to a set to instantly remove duplicates:
items = ["apple", "banana", "apple", "orange", "banana"]
unique_items = set(items)
print(unique_items) # output with duplicates removed
Python sets are efficient for data cleanup, membership testing, and set algebra. They're also fast thanks to their hash-based internal structure—just like dictionaries!
The cleanest way to tidy up messy data? Use a set — and keep your code simple and powerful. Grow with CodeVerse every day ๐
Icons by Flaticon
Comments
Post a Comment