DEV Community

Cover image for Python Sets: Unlocking the Power of Unique Collections
Mary Nyandia
Mary Nyandia

Posted on

Python Sets: Unlocking the Power of Unique Collections

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)

Enter fullscreen mode Exit fullscreen mode

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)

Enter fullscreen mode Exit fullscreen mode

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'}

Enter fullscreen mode Exit fullscreen mode

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)

Enter fullscreen mode Exit fullscreen mode

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)