Python Introduction to Sets
Table of Contents
In the last lesson, we learned about Python Tuple vs List. Now let’s use sets to store unique values without duplicates.
Let’s Talk About a Different Kind of Collection
We know about lists. We know about tuples. Both are ordered collections. Lists are mutable. Tuples are immutable.
Now let’s talk about sets.
A set is a collection of items, but with two special rules.
First, sets are unordered. That means the items do not have a fixed position. We cannot access them by index. We cannot say “give me the first item.” Because there is no first item.
Second, sets contain only unique items. No duplicates. If we try to add the same item twice, it will only be stored once.
Think of it like a bag of marbles. We can put marbles in. But we cannot have two identical marbles. If we try to add a red marble when there is already a red marble, it just does not get added again. And the marbles are all mixed up. We cannot say which one is first or last.
That is a set.
How to Create a Set in Python
We create a set by putting items inside curly braces { }, separated by commas.
fruits = {"apple", "banana", "orange"}numbers = {1, 2, 3, 4, 5}That is a set. Just like a list or tuple, but with curly braces.
We can also use the set() function to create a set from another iterable.
numbers = set([1, 2, 2, 3, 3, 3])print(numbers)Output
{1, 2, 3}Notice how the duplicates were removed. That is one of the main features of sets.
An Empty Set in Python
Let’s be careful with empty sets. We cannot use {} for an empty set. That creates an empty dictionary.
empty = {}print(type(empty))Output
<class 'dict'>To create an empty set, we use set().
empty = set()print(type(empty))Output
<class 'set'>That is a common gotcha. Let’s remember it.
Sets Are Unordered in Python
Sets do not keep items in any particular order. When we print a set, the order may look random. And it can change between runs.
fruits = {"apple", "banana", "orange"}print(fruits)Output (may vary):
{'banana', 'orange', 'apple'}So let’s not rely on the order of items in a set. If we need order, we use a list or tuple.
Sets Contain Unique Items
This is the most useful feature. Sets automatically remove duplicates.
numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]unique_numbers = set(numbers)print(unique_numbers)Output
{1, 2, 3, 4}That is very handy when we want to remove duplicates from a list.
Adding Items to a Set in Python
We can add items using the add() method.
fruits = {"apple", "banana"}fruits.add("orange")print(fruits)Output
{'apple', 'banana', 'orange'}If we try to add an item that already exists, nothing happens. No error.
fruits.add("apple")print(fruits)Output
{'apple', 'banana', 'orange'}Still the same set. Because duplicates are not allowed.
Removing Items from a Set in Python
We can remove items using remove() or discard().
remove() raises an error if the item is not found.
fruits = {"apple", "banana", "orange"}fruits.remove("banana")print(fruits)Output
{'apple', 'orange'}fruits.remove("grape") # Error!discard() does not raise an error. It just does nothing if the item is not there.
fruits.discard("grape") # No errorprint(fruits)Output
{'apple', 'orange'}We can also use pop() to remove and return an arbitrary item. Because sets are unordered, we do not know which item will be removed.
fruits = {"apple", "banana", "orange"}removed = fruits.pop()print(removed)print(fruits)Output (may vary):
banana{'apple', 'orange'}Let’s use pop() carefully. It is not predictable which item will be removed.
Checking If an Item Is in a Set
We use in.
fruits = {"apple", "banana", "orange"}print("banana" in fruits)Output
Trueprint("grape" in fruits)Output
FalseThis is very fast. Sets are optimized for membership checks. Much faster than lists for large collections.
Looping Through a Set in Python
We can loop through a set with a for loop.
fruits = {"apple", "banana", "orange"}for fruit in fruits: print(fruit)Output (order may vary):
bananaorangeappleAgain, the order is not guaranteed. But we can still loop through all items.
Length of a Set in Python
We use len().
fruits = {"apple", "banana", "orange"}print(len(fruits))Output
3Why Use Sets in Python?
Sets are useful when:
- We need to remove duplicates from a collection.
- We need to check membership quickly.
- We need to perform mathematical set operations like union, intersection, difference.
- We do not care about order.
Python Sets: A Real-Life Example
Let’s say we have a list of email addresses. But some people signed up twice. We want to find the unique emails.
emails = [ "alex@example.com", "sam@example.com", "alex@example.com", "john@example.com", "sam@example.com"]
unique_emails = set(emails)print(unique_emails)Output
{'alex@example.com', 'john@example.com', 'sam@example.com'}That is a quick way to clean up duplicates.
Another Example — Checking Common Interests
alex_interests = {"reading", "coding", "gaming"}sam_interests = {"coding", "music", "gaming"}
common = alex_interests & sam_interestsprint(common)Output
{'coding', 'gaming'}The & operator gives the intersection. That is one of the set operations we will cover in later articles.
Common Mistakes with Python Sets
Mistake 1: Using for an Empty Set
empty = {}print(type(empty)) # <class 'dict'>So what do we do? We use set().
empty = set()Mistake 2: Trying to Access Items by Index
fruits = {"apple", "banana"}print(fruits[0]) # Error!Sets do not support indexing. Because they are unordered.
Mistake 3: Thinking Sets Keep Order
fruits = {"apple", "banana", "orange"}print(fruits)The order might not be what we expect. Let’s not rely on it.
Mistake 4: Using remove() Without Checking
fruits = {"apple"}fruits.remove("banana") # Error!So what do we do? We use discard() or check first.
fruits.discard("banana") # No errorNext, we will learn about Python Set Operations and combine or compare sets in useful ways.