Creating Sets
Sets are collections of unique, unordered items. They’re perfect when you need distinct values without duplicates.
colors = {"red", "green", "blue"}
print("Set:", colors)
Adding and Removing Items
Sets are mutable, so you can add new elements with add() or remove them with discard(). Unlike lists, sets don’t preserve order, so items may appear in different sequences when printed.
colors.add("yellow")
colors.discard("green")
print(colors)
Handling Duplicates
Sets automatically eliminate duplicates. This feature ensures your data remains clean and unique, saving you from manually checking for repeated values.
items = {"apple", "apple", "banana"}
print(items) # {'apple', 'banana'}
Set Operations
Sets support mathematical operations like union, intersection, and difference. These operations are powerful for comparing datasets — for example, finding shared interests between users or identifying unique items in two collections.
a = {"red", "blue"}
b = {"blue", "green"}
print("Union:", a | b)
print("Intersection:", a & b)
print("Difference:", a - b)
My take
Sets keep your data clean by automatically removing duplicates and provide powerful operations like union, intersection, and difference. They’re perfect for tasks involving uniqueness and comparisons.
Top comments (0)