Python sets and tuples
Choose uniqueness or immutable grouping to fit the problem.
On this page
Lists and basic collection syntax.
- Choose uniqueness or immutable grouping to fit the problem.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
A set stores distinct hashable elements and supports union, intersection, and difference. Set iteration order is not a sorted-order contract, so sorted is used for display.
A tuple groups values in an immutable sequence. It can be a dictionary key when every contained element is hashable. An immutable tuple can still refer to a mutable object.
Code example
first = {1, 2, 3}
second = {3, 4}
print(sorted(first & second))
print(sorted(first | second))
point = (2, 5)
x, y = point
print(x + y)
assert len({1, 1, 2}) == 2[3] [1, 2, 3, 4] 7
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
first = {1, 2, 3}second = {3, 4}print(sorted(first & second))print(sorted(first | second))point = (2, 5)x, y = pointprint(x + y)assert len({1, 1, 2}) == 2Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Create three unique elements. | first = {1, 2, 3} | — | |
| Create another set. | second = {3, 4} | — | |
| Intersection keeps the shared element. | second = {3, 4} | [3] | |
| Union includes each distinct element once. | second = {3, 4} | [3] [1, 2, 3, 4] | |
| Unpack the two-element tuple. | x = 2, y = 5 | [3] [1, 2, 3, 4] | |
| Add the coordinates. | x = 2, y = 5 | [3] [1, 2, 3, 4] 7 |
Behind the scenes
How Python processes this code
Python runs this source through its interpreter. It creates objects for values and resolves names as each statement runs.
Cost and common mistakes
Expected linear set-combination work in the input sizes under normal hashing; sorting the result adds O(k log k) time and O(k) storage.
- {} creates an empty dictionary; use set() for an empty set.
- A tuple containing a list is not hashable.
Try it yourself
Calculate sorted(first - second).
Reveal answer and reasoning
The result is [1, 2], the elements only in first.