Python · Chapter 16 of 45
Python Tuples
A tuple is like a list but IMMUTABLE — once created you cannot change its contents. Create with `()` or just commas: `x = 1, 2, 3`.
Use tuples for fixed collections: coordinates, RGB colors, database rows.
Why immutable?
Immutability makes tuples hashable, so they can be dict keys or set members.
Unpacking
You can unpack a tuple into variables: `x, y = (10, 20)`. This is how functions return multiple values.
Example 1 (python)
point = (3, 4)
x, y = point
print("x =", x, "y =", y)Output
x = 3 y = 4Unpack tuple into two variables.
Example 2 (python)
single = (42,) # note the comma
print(type(single))Output
<class 'tuple'>A one-element tuple needs a trailing comma.
Key points
- Immutable — cannot be changed after creation.
- Created with `()` or commas.
- Can be dict keys or set members.
- Common for returning multiple values from a function.
💡 Note: A single-element tuple needs a comma: `(42,)`. Without the comma `(42)` is just an integer in parentheses.
