Tuples and Unpacking
Group a few values together, then hand them out in one clean line
(3, 5). It is a lot like a list, but with one special rule: once you make a tuple, you cannot change it. Tuples are perfect for values that belong together and should stay put.
- build a tuple and read items from it,
- explain what immutable means,
- use packing and unpacking to move values around,
- do multiple assignment like
a, b = 1, 2and swap two values, - return more than one value from a function,
- decide when a tuple is a better fit than a list.
1. What is a tuple?
Think about a pair of shoes, or the two coordinates on a map like (row 3, seat 5). These are values that naturally travel together. A tuple lets you keep such values as one neat package.
You already met lists earlier in this course. A tuple is very close to a list: it is ordered (the items keep their positions) and it can hold any kind of value. The one big difference is the brackets and the rule that comes with them:
- A list uses square brackets:
[3, 5]— and you can change it later. - A tuple uses round brackets:
(3, 5)— and it is locked once made.
A good picture is a sealed gift box. You put things inside, tape it shut, and after that nobody can add, remove, or swap what is inside. That "sealed" quality has a name in Python: immutable, which simply means "cannot be changed".
point = (3, 5)
print(point)
print(type(point))
Output:
(3, 5)
<class 'tuple'>
The word tuple in the output is Python telling you the type of value you made.