Set in Python
A set stores each value only once and answers "is this value in here?" very quickly, which makes it ideal for removing duplicates.
What is Set?
A set stores each value only once and answers "is this value in here?" very quickly, which makes it ideal for removing duplicates.
Keep unique values with a Python set and combine sets with union and intersection.
When should you use it?
- Learn Python syntax through a practical example.
- Build a foundation for larger programming problems.
- Test an idea quickly without a local setup.
See how it works
Pick an operation to highlight its result in the diagram. Add a value that is already in the set to see that duplicates are ignored.
Example code
# A set stores unique values with no fixed order.
tags = {"python", "code", "python", "learn"}
print(len(tags)) # the duplicate "python" is kept once
print("code" in tags) # fast membership test
tags.add("fun")
tags.discard("code")
print(sorted(tags))
# Remove duplicates from a list.
numbers = [3, 1, 3, 2, 1]
print(sorted(set(numbers)))
# Set operations.
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(a | b) # union: in either set
print(a & b) # intersection: in both
print(a - b) # difference: in a but not in b
Expected output
3
True
['fun', 'learn', 'python']
[1, 2, 3]
{1, 2, 3, 4, 5}
{3, 4}
{1, 2}
How it works
Sets have no fixed order, so sorted() is used for stable output. | builds the union, & the intersection and - the difference of two sets.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change the input and predict the output before running.
- Handle empty or invalid input.
- Wrap the logic in a function and add more test cases.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
All challenges