Python Sets



A Set in Python is a collection of items where:

What Does a Set Look Like?

You can create a set using curly braces {} or the set() function.

fruits = {"apple", "banana", "orange"}
print(fruits)
{'banana', 'orange', 'apple'}

Note: The order might look different when you run it. That’s okay — sets are unordered, so the order is not fixed.

Why Use Sets?

Removing Duplicates Example

numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = set(numbers)
print(unique_numbers)
{1, 2, 3, 4, 5}

Why? Because sets automatically remove duplicates!

Basic Set Operations (CRUD)

Let’s learn the basic operations on sets: Create, Read, Update, and Delete.

1. Create a Set

colors = {"red", "green", "blue"}

2. Read Items

You can’t read by position, but you can check if something exists:

print("green" in colors)  # True
print("yellow" in colors) # False

3. Add Items

colors.add("yellow")
print(colors)
{'red', 'green', 'blue', 'yellow'}

4. Remove Items

You can use remove() or discard():

colors.remove("green")   # Removes green
colors.discard("pink")   # Does nothing (pink not found)
print(colors)
{'red', 'blue', 'yellow'}

5. Clear All Items

colors.clear()
print(colors)
set()

This means the set is now empty.

Conclusion

Sets are perfect when you want to keep only unique items and don’t care about the order. They are simple, fast, and super useful when removing duplicates or checking membership.

In the next topics, we’ll explore how sets can be compared and combined using set operations like union, intersection, and difference!



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M