Skip to main content

What are Sets?

A Set is an unordered collection of unique items. If you put duplicate items into a set, Python automatically throws away the extras and keeps only one copy.

Think of a set like:

  • A bowl of different fruit flavors (no two candies are the exact same flavor)
  • A guest list where people who RSVP twice are only listed once

Creating Sets

You create a set using curly braces {} with items inside, or by using the set() function:

# A set of colors
colors = {"red", "blue", "green", "red"}

# Notice that the duplicate "red" disappears automatically!
print(colors) # Output: {'blue', 'green', 'red'}

:::warning Empty Set Trap To create an empty set, you must use set(). Typing {} creates an empty Python Dictionary instead!

# Wrong - creates an empty dictionary
wrong_set = {}
print(type(wrong_set)) # <class 'dict'>

# Right - creates an empty set
clean_set = set()
print(type(clean_set)) # <class 'set'>

:::

Removing Duplicates from a List

The most common real-world use case for a set is cleaning up duplicates from a list:

raw_emails = ["user@test.com", "admin@test.com", "user@test.com"]

# Convert to a set to drop duplicates, then back to a list
clean_emails = list(set(raw_emails))
print(clean_emails) # Output: ['user@test.com', 'admin@test.com']

Sets Have No Index Numbers

Because sets store items in an unordered way, there is no index 0 or index 1. You cannot grab items using brackets []:

fruits = {"apple", "banana"}
# print(fruits[0]) # TypeError: 'set' object is not subscriptable

Adding and Removing Items (add, remove, discard)

  • .add(item) adds a single new item.
  • .remove(item) removes an item, but throws an error if the item is not found.
  • .discard(item) safely removes an item without throwing an error if it is missing.
tags = {"python", "ai"}

tags.add("data")
print(tags) # Output: {'python', 'data', 'ai'}

tags.discard("java") # Safe! No error raised even though "java" isn't inside.

Common Beginner Mistakes

Trying to access set items by index
# Wrong - sets have no order or index positions
numbers = {10, 20, 30}
print(numbers[0]) # TypeError!

# Right - use a loop or check membership with 'in'
if 10 in numbers:
print("10 is in the set")

What's Next?

Let's explore mathematical set operations like combining sets (union), finding overlaps (intersection), and finding differences.