LearnWave
Learn it. Master it.

Tuples and Dictionaries

Tuples

Create a tuple, including a one-element tuple.

A tuple is an ordered sequence of elements of any type, written in round brackets and separated by commas:

  • (1, 2, 3, 4, 5)
  • ('Economics', 87, 'Accountancy', 89.6)
  • (10, 20, 30, [40, 50])

A tuple with one element needs a comma: (7,) is a tuple, but (7) is just the number 7 in brackets. A comma-separated sequence without brackets is also a tuple: t = 4, 5 makes the tuple (4, 5).

Elements are reached by indexing and slicing, exactly as for lists: t[0], t[-1], t[1 + 2]. An index out of range gives an IndexError.

The big difference from lists: tuples are immutable. Once made, their elements cannot be changed: trying t[0] = 10 gives TypeError: 'tuple' object does not support item assignment. This makes tuples good for fixed data, such as the days of the week.

One subtle point: if a tuple contains a mutable element, such as a list, that list itself can still be changed. In t = (5, 6, ['a', 'b']), the statement t[2][0] = 'z' makes t equal to (5, 6, ['z', 'b']). The tuple still holds the same list; only the list's contents have changed.

(7,) is a tuple; (7) is a number.

Practise this lesson

Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.

No account, no email address. Opens the real product.