Lesson 4 of 10
A tuple is like a list, but immutable — once created, it cannot be changed. You write it with parentheses instead of square brackets.
point = (3, 5)
print(point)
print(point[0])
print(len(point))
Indexing, slicing, len(), in, and looping all work exactly as they do on lists.
What you cannot do
point = (3, 5)
point[0] = 10
That raises TypeError: 'tuple' object does not support item assignment. There is no append,
no remove, no sort — those methods simply do not exist on tuples.
Why would you want that?
Immutability sounds like a downside, but it is a feature:
- Safety. If a value should never change — a coordinate, an RGB colour, a date — a tuple makes accidental modification impossible instead of merely unlikely.
- Intent. Seeing a tuple tells the next reader "this is a fixed record, not a growing collection."
- Usable as dictionary keys. You'll see this in the next lesson: dictionary keys must be immutable, so a tuple can be a key and a list cannot.
Creating tuples
empty = ()
single = (42,)
several = (1, 2, 3)
no_parens = 1, 2, 3
print(type(single))
print(no_parens)
Watch the single-item case: (42) is just the number 42 in parentheses. The trailing comma in
(42,) is what makes it a tuple.
Unpacking
This is where tuples really earn their place. You can assign every element to its own variable in one line:
point = (3, 5)
x, y = point
print(x)
print(y)
The number of variables must match the number of items. Unpacking also gives you the neatest swap in any language:
a = 1
b = 2
a, b = b, a
print(a, b)
Converting between the two
numbers = (3, 1, 2)
as_list = list(numbers)
as_list.sort()
print(tuple(as_list))
If you need to modify a tuple, convert it to a list, change it, and convert back — you get a new tuple, and the original is untouched.
Try it yourself
Unpack the tuple into x and y, then print their sum.
Checkpoint
- Tuples use
(parens)and cannot be changed after creation. - A one-item tuple needs a trailing comma:
(42,). - Unpacking assigns each element to its own variable, and enables
a, b = b, a. - Use a tuple for fixed records; use a list for collections that grow and change.
Questions about this lesson
Log in to ask a question.