Skip to main content
Editor

Python Sets: Unique Collections, Operations, and Use Cases

Intermediate20 min7 exercises115 XP

Leer en españolЧитать на русскомLer em portuguêsอ่านภาษาไทย

0/7 exercises

Imagine you're a teacher taking attendance. A student accidentally signs the attendance sheet twice. Does that mean they're in class twice? Of course not. You only care about who showed up, not how many times they wrote their name.

A Python set works the same way. It's a collection that automatically removes duplicates. Every item in a set is unique. Sets also don't care about order - they just care about membership.

In this tutorial, you'll learn how to create sets, perform powerful operations like union and intersection, modify sets with methods, and discover when sets are the perfect tool for the job.

How to Create a Set in Python

You create a set by placing items inside curly braces {}, separated by commas. If you add duplicate values, Python quietly ignores them.

Creating sets with curly braces
# A basic set of fruits
fruits = {'apple', 'banana', 'cherry'}
print(fruits)
# Duplicates are automatically removed
colors = {'red', 'blue', 'red', 'green', 'blue'}
print(colors) # Only 3 unique colors
Output
{'apple', 'banana', 'cherry'}
{'red', 'green', 'blue'}

Notice that the output order might look different from what you typed. Sets are unordered, so Python can store items in any arrangement internally. Don't rely on sets to keep a specific order.

You can also create a set from a list using the set() constructor. This is a popular way to remove duplicates from a list.

Creating sets with the set() constructor
# Convert a list with duplicates into a set
names_list = ['Alice', 'Bob', 'Alice', 'Charlie', 'Bob']
names_set = set(names_list)
print(names_set) # Only unique names
# Create a set from a string (each character becomes an item)
letters = set('hello')
print(letters) # {'h', 'e', 'l', 'o'} - only one 'l'
Output
{'Bob', 'Alice', 'Charlie'}
{'o', 'l', 'e', 'h'}

Set Operations: Union, Intersection, and Difference

The real power of sets comes from set operations. These let you combine, compare, and find differences between sets. Think of them like Venn diagrams from math class.

Union: Combine Everything Together

A union gives you all items from both sets, without duplicates. You can use the | operator or the .union() method.

Union combines all unique items
math_students = {'Alice', 'Bob', 'Charlie'}
science_students = {'Bob', 'Diana', 'Charlie'}
# Union - everyone in either class
all_students = math_students | science_students
print(all_students)
# Same thing using the method
all_students = math_students.union(science_students)
print(all_students)
Output
{'Charlie', 'Bob', 'Alice', 'Diana'}
{'Charlie', 'Bob', 'Alice', 'Diana'}

Intersection: Find What's in Common

An intersection gives you only the items that appear in both sets. Use the & operator or .intersection().

Intersection finds common items
math_students = {'Alice', 'Bob', 'Charlie'}
science_students = {'Bob', 'Diana', 'Charlie'}
# Intersection - students in BOTH classes
both_classes = math_students & science_students
print(both_classes) # {'Bob', 'Charlie'}
Output
{'Bob', 'Charlie'}

Difference: What's Unique to One Set

A difference gives you items that are in the first set but not in the second. Use the - operator or .difference(). The order matters here.

Difference finds items unique to one set
math_students = {'Alice', 'Bob', 'Charlie'}
science_students = {'Bob', 'Diana', 'Charlie'}
# Who is ONLY in math?
math_only = math_students - science_students
print(math_only) # {'Alice'}
# Who is ONLY in science?
science_only = science_students - math_students
print(science_only) # {'Diana'}
Output
{'Alice'}
{'Diana'}

Symmetric Difference: Items in One but Not Both

A symmetric difference gives you items that are in either set, but not both. Think of it as the opposite of intersection. Use the ^ operator or .symmetric_difference().

Symmetric difference excludes shared items
math_students = {'Alice', 'Bob', 'Charlie'}
science_students = {'Bob', 'Diana', 'Charlie'}
# Students in only ONE class (not both)
exclusive = math_students ^ science_students
print(exclusive) # {'Alice', 'Diana'}
Output
{'Alice', 'Diana'}

How to Add and Remove Items from a Set

Sets are mutable, meaning you can add and remove items after creation. Here are the key methods you'll use.

Adding and removing set items
fruits = {'apple', 'banana'}
# Add a single item
fruits.add('cherry')
print(fruits)
# Add multiple items at once
fruits.update(['date', 'elderberry'])
print(fruits)
# Remove an item (raises error if not found)
fruits.remove('banana')
print(fruits)
# Discard an item (no error if not found)
fruits.discard('mango') # No crash!
print(fruits)
Output
{'apple', 'banana', 'cherry'}
{'date', 'elderberry', 'apple', 'banana', 'cherry'}
{'date', 'elderberry', 'apple', 'cherry'}
{'date', 'elderberry', 'apple', 'cherry'}

You can also clear all items or pop an arbitrary item from the set (you don't get to choose which one).

Pop and clear methods
numbers = {10, 20, 30, 40, 50}
# Pop removes and returns an arbitrary item
removed = numbers.pop()
print(f'Removed: {removed}')
print(f'Remaining: {numbers}')
# Clear removes everything
numbers.clear()
print(numbers) # set()
Output
Removed: 50
Remaining: {20, 40, 10, 30}
set()

Why Sets Are Lightning-Fast for Membership Testing

One of the best reasons to use a set is checking if something exists. The in keyword works with both lists and sets, but sets are dramatically faster.

Fast membership testing with in
allowed_users = {'alice', 'bob', 'charlie', 'diana'}
user = 'bob'
if user in allowed_users:
print(f'{user} is allowed!')
else:
print(f'{user} is not allowed.')
# Checking who is NOT in the set
user2 = 'eve'
if user2 not in allowed_users:
print(f'{user2} is not on the list.')
Output
bob is allowed!
eve is not on the list.

What Are Frozensets?

A frozenset is an immutable version of a set. Once created, you cannot add or remove items. This makes frozensets hashable, meaning they can be used as dictionary keys or stored inside other sets.

Frozensets are immutable sets
# Create a frozenset
vowels = frozenset(['a', 'e', 'i', 'o', 'u'])
print(vowels)
# You can still do set operations
consonants = frozenset(['b', 'c', 'd', 'f', 'g'])
all_letters = vowels | consonants
print(all_letters)
# But you CANNOT modify it
# vowels.add('y') # AttributeError!
Output
frozenset({'u', 'o', 'i', 'e', 'a'})
frozenset({'u', 'o', 'i', 'f', 'g', 'd', 'e', 'b', 'c', 'a'})

When Should You Use a Set Instead of a List?

Sets and lists solve different problems. Here's a simple rule: if you care about order or duplicates, use a list. If you care about uniqueness or fast lookups, use a set.

Use a List when...
# Order matters
playlist = ['song1', 'song2', 'song3']

# Duplicates are meaningful
die_rolls = [3, 5, 3, 2, 5, 6]

# You need index access
first = playlist[0]
Use a Set when...
# Only unique items matter
tags = {'python', 'coding', 'tutorial'}

# Fast membership checks
if 'python' in tags:
    print('Found!')

# Removing duplicates
unique = set([1, 2, 2, 3, 3])

Practice Exercises

Remove Duplicates from a List
Write Code

You have a list of email addresses where some appear more than once. Create a set called unique_emails from the emails list and print it sorted alphabetically using sorted().

emails = ['alice@mail.com', 'bob@mail.com', 'alice@mail.com', 'charlie@mail.com', 'bob@mail.com']
# Create a set of unique emails and print them sorted
Predict the Set Output
Predict Output

What does this code print? Think carefully about how sets handle duplicates and what the len() function returns.

data = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
unique = set(data)
print(len(unique))

Write a print() statement with the exact output.

# What does this code print?
data = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
unique = set(data)
print(len(unique))
Find Students in Both Classes
Write Code

You have two sets: math and english. Find and print the students who are enrolled in both classes. Print the result as a sorted list.

math = {'Alice', 'Bob', 'Charlie', 'Diana'}
english = {'Bob', 'Diana', 'Eve', 'Frank'}
# Find students in both classes and print sorted
Fix the Empty Set Bug
Fix the Bug

This code tries to create an empty set, add items to it, and print the result. But there's a bug - the programmer used {} to create an empty set. Fix the bug so the code works correctly.

# Bug: this creates a dictionary, not a set!
my_set = {}
my_set.add('python')
my_set.add('java')
my_set.add('python') # duplicate
print(sorted(my_set))
Find Missing Ingredients
Write Code

You have a recipe set with all required ingredients and a pantry set with what you already have. Find the ingredients you still need to buy and print them as a sorted list.

recipe = {'flour', 'sugar', 'eggs', 'butter', 'vanilla'}
pantry = {'flour', 'eggs', 'salt', 'pepper'}
# Find and print what you need to buy (sorted)
Deduplicate While Preserving Order
Write Code

Write a function called dedupe(items) that removes duplicates from a list while preserving the original order. Use a set to track which items you've already seen. Return the deduplicated list.

Test it by calling print(dedupe([3, 1, 4, 1, 5, 9, 2, 6, 5, 3])).

def dedupe(items):
# Use a set to track seen items
# Build a new list with only first occurrences
pass
print(dedupe([3, 1, 4, 1, 5, 9, 2, 6, 5, 3]))
Members of Exactly One Club
Stretch

A school keeps a dictionary of clubs: each key is a club and each value is a list of its members (a list may name someone twice by mistake). Write a function in_one_club(clubs) that returns, as a sorted list, the people who belong to exactly one club.

in_one_club({"chess": ["ana", "ben"], "drama": ["ben", "cal"]})   # ['ana', 'cal']

ben is in two clubs, so the answer leaves ben out. There can be any number of clubs. Try to solve it with set operations.

Return the answer instead of printing it: Check calls in_one_club() with its own clubs, some of them hidden.

def in_one_club(clubs):
pass
Solution unlocks after your first Check

Harder problems

More problems on this topic: Dictionaries and sets

Related Tutorials

Was this tutorial helpful?