Sets in Python: The Magic of Unique Collections (Goodbye Duplicates!)🪄✨

In partnership with

TL;DR

Sets in Python are the go-to data structure for storing items without duplicates, making them perfect for handling unique data.

In this post, we’ll explore how sets work, why they’re useful, and some fun Python examples to help you master this magical, duplicate-free collection!

What You’ll Learn:

  • Characteristics of sets and how they differ from lists and dictionaries

  • How to create, add to, and work with sets in Python

  • Practical use cases for sets and why they’re useful in real-world coding

What Is a Set? ✨

A set in Python is like an enchanted box that only accepts unique items.

No matter how many times you try to add the same thing, the set will only keep one copy.

Imagine a treasure chest that refuses to duplicate items—no endless piles of gold, just one piece of each!

Sets are unordered collections of unique items, which means that:

  1. There’s no fixed order—you can’t rely on items to stay in a specific position.

  2. Duplicates aren’t allowed—try to add the same item twice, and the set will keep only one of them.

Key Characteristics of Sets 🗝️

  1. Unique Items Only: Sets automatically remove duplicates, making them perfect for storing unique values.

  2. Unordered: Sets don’t maintain any specific order, so each time you view the set, the order may look different.

  3. Mutable: You can add or remove items from a set after creating it, but each item must be hashable (basically, immutable data like strings or numbers).

Why Use Sets? Benefits of Sets

Benefits

  • Efficient for Uniqueness: Sets automatically keep only unique items, which saves time if you’re filtering out duplicates.

  • Fast Membership Testing: Checking if an item exists in a set is much faster than checking in a list.

  • Great for Mathematical Operations: Sets allow easy union, intersection, and difference operations, making them useful in many algorithms.

Drawbacks

  • No Duplicates: If you need duplicates, use a list instead.

  • No Order: Sets are unordered, so if you need a specific order, a set might not be the best choice.

Just like Python sets ensure unique items without duplicates, Pinata simplifies app building and file sharing by securely managing your data with its IPFS API and Gateways. Keep your content unique, accessible, and organized with Pinata’s powerful tools!

Add file uploads instantly with Pinata’s developer-friendly File API

As a developer, your time is valuable. That’s why Pinata’s File API is built to simplify file management, letting you add uploads and retrieval quickly and effortlessly. Forget the headache of complex setups—our API integrates in minutes, so you can spend more time coding and less time on configurations. With secure, scalable storage and easy-to-use endpoints, Pinata takes the stress out of file handling, giving you a streamlined experience to focus on what really matters: building your app.

Let’s Code: Creating and Using Sets in Python 🐍

To make things fun, let’s imagine a magical set that stores unique items found in a treasure hunt.

Each item can only appear once—no duplicate potions here!

Step 1: Creating a Set

# A set of unique treasure items

treasure_set = {"Magic Wand", "Potion", "Golden Key", "Crystal Ball"}

print("Treasure Set:", treasure_set)

What’s Happening? 

We just created a set called treasure_set.

Unlike lists, this collection doesn’t keep items in a specific order, and it ensures that each item is unique.

Creating a Set

Step 2: Adding Items to a Set

Our treasure hunt continues, and we’ve found a Magic Wand and a Silver Coin.

Let’s try adding them to the set.

# Adding new items to the set

treasure_set.add("Silver Coin")

treasure_set.add("Magic Wand")  # This is already in the set

print("Updated Treasure Set:", treasure_set)

Explanation

Adding Silver Coin works perfectly, but when we try to add Magic Wand again, the set ignores the duplicate.

Only unique items are allowed in sets!

Adding Items to a Set

Step 3: Removing an Item from a Set

Uh-oh, we lost the Potion!

Let’s remove it from the treasure set.

# Removing an item from the set

treasure_set.remove("Potion")

print("Treasure Set After Removal:", treasure_set)

Explanation

Using .remove() lets us take the Potion out of the set.

Be careful—if you try to remove an item that doesn’t exist, Python will throw an error.

Removing an Item from a Set

Step 4: Checking Membership in a Set

Want to see if the Golden Key is still in our collection?

Sets make it easy to check for specific items.

# Checking if an item is in the set

print("Is Golden Key in the treasure set?", "Golden Key" in treasure_set)  # Output: True

print("Is Potion in the treasure set?", "Potion" in treasure_set)  # Output: False

How It Works:

The in keyword lets you check for an item instantly.

Sets are optimized for this, so it’s faster than checking a list!

Checking Membership in a Set

Step 5: Combining Sets with Magical Operations

Imagine we found a new set of items from a second treasure hunt!

Sets make it easy to merge collections or find common items.

# Another set of unique treasure items

more_treasures = {"Dragon Scale", "Silver Coin", "Magic Map", "Golden Key"}

# Union: Combine both sets (no duplicates)

all_treasures = treasure_set.union(more_treasures)

print("All Unique Treasures:", all_treasures)

# Intersection: Find items common to both sets

common_treasures = treasure_set.intersection(more_treasures)

print("Common Treasures:", common_treasures)

Explanation

  • .union() combines the sets, creating one set with only unique items.

  • .intersection() finds only the items that both sets have in common. 

These operations make sets perfect for situations where you need to combine or compare data quickly.

Combining Sets with Magical Operations

When to Use Sets vs. Lists vs. Dictionaries

Here’s a quick guide:

  • Use a Set when you need unique items and don’t care about order.

  • Use a List if you want ordered items or need duplicates.

  • Use a Dictionary for pairs of data where each item has a unique key.

Final Thoughts

Sets are like the magic organizers of Python—perfect for handling unique items, merging data, and finding overlaps quickly. 

Whether you’re collecting treasures, processing data, or filtering out duplicates, sets are a powerful tool that will make your coding more efficient.

In our next post, we’ll dive into tuples, a data structure that combines the best of both worlds with immutability. 

Until then, keep your code clean, unique, and magical! 🪄✨

Let’s Inspire Future AI Coders Together! ☕

 

I’m excited to continue sharing my passion for Python programming and AI with you all.

If you’ve enjoyed the content and found it helpful, do consider supporting my work with a small gift.

Just click the link below to make a difference – it’s quick, easy, and every bit helps and motivates me to keep creating awesome contents for you.

Thank you for being amazing!

🎉 We want to hear from you! 🎉 How do you feel about our latest newsletter? Your feedback will help us make it even more awesome!

Login or Subscribe to participate in polls.