Collections
Sets and unique values
Remove duplicates with a set and test membership without relying on order.
Lesson 21 of 63
Reading: about 2 min
Lesson + practice: about 10 min
Difficulty: Beginner
On this page4 sections
A set contains unique values. It does not provide list-style indexing, and you should not rely on its iteration order. Use a set when uniqueness or membership matters.
subjects = {"Python", "SQL", "Python"}
print(len(subjects))
print("SQL" in subjects)
subjects.add("Excel")
print("Excel" in subjects)2 True True
Create a set from another collection
Use set() to remove duplicate values from a list. Use set() with no arguments to make an empty set; {} creates an empty dictionary.
topics = ["loops", "files", "loops"]
unique_topics = set(topics)
print(len(unique_topics))
print("loops" in unique_topics)2 True
Why this works
A set is useful when you care whether a value is present or how many distinct values you have. Duplicate entries collapse into one. Sets are not position-based: membership works, but indexing does not. Convert to a sorted list only when you need a predictable display order.
Practice
Create a list containing repeated topic names, convert it to a set, and check its length. Do not assume a particular order when printing the set.
Does {} create an empty set?
Reveal answer
No. It creates an empty dictionary; use set() for an empty set.
Try another case
How many values remain in set(["SQL", "Python", "SQL", "Excel"])?
Check your answer
Reveal answer
Three distinct values remain: SQL, Python, and Excel.
Your progress
Reveal the check answer or reach the end to complete this lesson.