Set
- Python course
- Beginner
- Lesson 66/116
- 4 min
Learn unique-element sets with {1, 2, 3}.
Set
A set is an unordered, unique collection. It is written with curly braces:
fruits = {"apple", "banana", "cherry"}
print(len(fruits)) # 3A set has two key properties: item order does not matter, and each item appears only once. This makes it handy for deduplication.
An empty set is created with set(); {} is an empty dict, not a set.
Set operations
Sets support mathematical set operations: union (|), intersection (&), difference (-):
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # {1, 2, 3, 4, 5}
print(a & b) # {3}
print(a - b) # {1, 2}These operations are fast and readable. Membership tests with in are much faster than lists.
Practice Deduplicate and print
Assign the list [1, 2, 2, 3, 3, 3] to nums. Assign set(nums) to unique. Then print print(sorted(unique)).
Starter code
# Deduplicate the listSample solution
nums = [1, 2, 2, 3, 3, 3]
unique = set(nums)
print(sorted(unique))Expected output
[1, 2, 3]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Avoid duplicates in a set
unique = {1, 2, 2, 3, 3, ____}
unique = {1, 2, 2, 3, 3, 3}
Explanation: {1, 2, 2, 3, 3, 3} becomes {1, 2, 3}.
2 Match the set operations
| Term | Meaning |
|---|---|
| |
Union |
& |
Intersection |
- |
Difference |
in |
Membership |
3 What does set([1, 1, 2, 2, 3]) produce?
- {1, 1, 2, 2, 3}
- (1, 2, 3)
- [1, 2, 3]
- {1, 2, 3} Correct answer
Explanation: A set removes duplicates, the result is {1, 2, 3}.