Tuple
- Python course
- Beginner
- Lesson 65/116
- 4 min
Learn immutable tuples with (a, b).
Tuple
A tuple is an immutable ordered data structure. It is written with parentheses:
point = (3, 4)
color = (255, 128, 0)A tuple is like a list but its items cannot be changed later. So it is preferred for fixed data: coordinates, RGB colors, weekdays and so on.
To define a one-element tuple, you need a trailing comma: (42,). Without parentheses, 42, is also a tuple.
Tuple index and slice
You access tuple items by index; slicing works as usual:
point = (3, 4)
print(point[0]) # 3
print(point[1:]) # (4,)Access is like a list; only assignment is forbidden. point[0] = 5 raises TypeError.
You can also loop over a tuple: for x in point:.
Practice Print tuple elements
Assign the tuple (3, 4) to point. Assign point[0] to x and point[1] to y. Then print print(x, y).
Starter code
# Define a coordinate with a tupleSample solution
point = (3, 4)
x = point[0]
y = point[1]
print(x, y)Expected output
3 4
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which of these is a tuple?
- [1, 2, 3]
- {1, 2, 3}
- (1, 2, 3) Correct answer
- {1: 2, 3: 4}
Explanation: (1, 2, 3) in parentheses is a tuple.
2 Access a tuple element
color = (255, 128, 0)
red = color[____]
color = (255, 128, 0)
red = color[0]
Explanation: color[0] gives the first item 255.
3 Match the tuple features
| Term | Meaning |
|---|---|
(1, 2, 3) |
Tuple syntax |
immutable |
Cannot change |
point[0] |
Index access |
for x in t |
Loop |