Tuples, like lists, are ordered collections of items. But different than lists, tuples are immutable – their contents cannot be modified.

Think of a tuple as a package which wraps some items: to change the items you need to ‘unwrap’ the package first, and then wrap the items again in a new package.

Tuple basics

Tuples are usually delimited by parentheses:

>>> aTuple = (1, 2, 'Hi')
>>> type(aTuple)
<type 'tuple'>

Tuples can also be written without the parentheses. As long as there is a comma, a sequence of items will be interpreted as a tuple:

>>> anotherTuple = 3, 4, 'Hello', 5
>>> type(anotherTuple)
<type 'tuple'>

Items in tuples can be accessed by their index, just like lists:

>>> aTuple[2]
Hi

However, unlike lists, items in tuples cannot be modified directly. Lists are mutable, but tuples are not.

For that reason, assigning a value to an item doesn’t work:

>>> aTuple[2] = 'bye'
Traceback (most recent call last):
  File "<untitled>", line 5, in <module>
TypeError: 'tuple' object does not support item assignment

To modify a tuple it is necessary to set all items as a package:

>>> aTuple = (1, 2, 'bye')
>>> aTuple
(1, 2, 'bye')

One-item tuples

Tuples with only one item require a comma to be recognized as a tuple. For example, this is not a tuple:

>>> aTuple = ('oops')
>>> type(aTuple)
<type 'str'>

To define a tuple with only one item we need to use a comma:

>>> aTuple = 'hi',
>>> type(aTuple)
<type 'tuple'>

Forgetting the comma in one-item tuples is a common beginner’s mistake.

Packing and unpacking tuples

Tuples are useful for wrapping a group of values into a single ‘thing’. For example, a color can be expressed as a tuple of (R, G, B) values, a position as a tuple of (x, y) coordinates, and so on. Since tuples are immutable, these values are kept together with some integrity.

Here’s an example of packing values into a tuple:

>>> color = 0, 255, 255
>>> color
(0, 255, 255)

If we need to use the values individually, we can do the opposite operation and unpack a tuple into variables:

>>> r, g, b = color
>>> r, g, b
(0, 255, 255)

Unpacking a tuple only works if the number of variable to the left of the equality matches the number of items in the tuple.

Here we have less variable names than values:

>>> x, y = color
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)

…and here we have more variable names than values. Notice how the error messages are different:

>>> k, l, m, n = color
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: not enough values to unpack (expected 4, got 3)
Last edited on 01/09/2021