Learn Python: The Fundamentals

In Python, a set is a collection that holds only unique values — no duplicates allowed. Unlike lists or tuples, sets are unordered, which means the items don’t follow any specific sequence. They’re incredibly useful when you want to filter out repeated data or compare different groups of values quickly and cleanly.

 

Creating Sets

To create a set, use curly braces {} or the set() function. If you add the same item more than once, Python will automatically keep just one copy of it.

 

numbers = {1, 2, 3, 3, 4}
print(numbers)    # Output: {1, 2, 3, 4}

 

Set Operations

One of the best things about sets is how easily you can compare them using operations like union, intersection, and difference. These are great when you’re working with multiple datasets or checking what values they share (or don’t).

 

a = {1, 2, 3}
b = {3, 4, 5}

print(a | b)   # Union: {1, 2, 3, 4, 5}
print(a & b)   # Intersection: {3}
print(a - b)   # Difference: {1, 2}

 

Membership and Modifying Sets

You can check if something is in a set using in, and you can update a set by adding or removing items. Just remember: since sets are unordered, you can’t access items by index like you would with a list.

 

fruits = {"apple", "banana"}
print("apple" in fruits)   # True

fruits.add("cherry")             # Add new item
fruits.remove("banana")          # Remove an item

print(fruits)              # Updated set

 

Interactive Exercise: Set Operations

Let’s try out some set operations. Create two sets and use union, intersection, and difference to compare their values.

 


# Create two sets
set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Perform set operations
print("Union:", set1 | set2)
print("Intersection:", set1 & set2)
print("Difference:", set1 - set2)

 
Use | for union, & for intersection, and - for difference.
 

Sets are perfect when you need to work with collections of unique items — like filtering out duplicates or comparing two datasets. They’re simple, fast, and surprisingly powerful once you start using them in real projects.