Tuples
Computer Science · Python
Question 1 of 10
0What does this Python code print? t = (2, 8, 5) print(t[0])
Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.
How to type your answer
- Fractions: 3/4. Mixed numbers: 1 1/2.
- Decimals with a point or a comma: 0.75 or 0,75.
- Negative numbers start with a minus: -3/4.
- Percentages need the % sign: 75%.
Stuck? Read the explanation
Unlocks at a streak of 5 correct answers in a row.
Embed this practice on your site or class page
Paste this HTML into your page. Students practise right there; it is free and needs no account.
Tuples explained
A tuple is an ordered, fixed collection of values, written in parentheses and separated by commas. Unlike a list, a tuple cannot be changed after it is created, which makes it suitable for values that should stay together.
A tuple groups related values, such as the x and y coordinates of a point. Tuples keep their order and can hold items of different types. Each item is read by its index, starting at 0.
The main difference from a list is immutability. You cannot assign to a tuple's items, add items or remove them. An attempt such as p[0] = 5 raises a TypeError. Because tuples cannot change, they can be used as dictionary keys and as set elements, which lists cannot.
A common trap is the one-item tuple. Parentheses alone do not make a tuple, so (5) is just the number 5. A trailing comma is needed, as in (5,).
Tuple unpacking assigns each item to its own variable in one statement. This is often used to return several values from a function.
Worked example
p = (4, 9)
x, y = p
print(x + y)
- Unpacking gives and .
- The sum is .
Swapping two variables works the same way: a, b = b, a rearranges both values without a temporary variable.
What you will practise
New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.
Example questions
Easy
What does this Python code print? t = (5, 7, 9) print(t[1])
Medium
What does this Python code print? t = (7, 6) + (3,) * 3 print(t.count(3))
Hard
What does this Python code print? first, *rest = (3, 9, 6, 6, 6, 8) print(sum(rest))