3.4.3. Tuples

3.4.3.1. Syntax

Python uses commas to create sequences of elements called tuples. The result is more readable if the tuple elements are enclosed in parentheses:

>>> X = (24, 3.14, 'w', 7) #  Tuple with 4 items
>>> Y = (100,)    # tuple with one item
>>> Z = () #empty tuple

The following is not a tuple:

>>> Q = (7)
>>> type(Q)
<type 'int'>
>>> Q == 7
True

Note that the parens made no difference. But the following is a tuple:

>>> T = (7,)
>>> type(T)
<type 'tuple'>

So is the following:

>>> R = 7,
>>> type(R)
<type 'tuple'>

Note that it’s the comma that matters. For this reason, you do not want to use unnecessary commas when typing Python commands, because you may unintentionally change the type of something into a tuple.

3.4.3.2. Making tuples

The tuple constructor function is the name of the type:

>>> L = tuple('hi!')  # make a string a tuple
>>> L
('h', 'i', '!')
>>> M = tuple()
>>> M
()

>>> X[0]   # 1st element
24
>>> X[1]   # 2nd element
3.1400000000000001
>>> X[-1]   # last element
7

As with lists and strings, you can check the contents of tuples. So:

>>> 24 in X
True
>>> 6 in X
False

Tuples also allow splicing, as lists do:

>>> X[0:2] # tuple of 1st and 2nd elements
(24, 3.1400000000000001)
>>> X[:-1] # tuple excluding last element

The following raises an IndexError:

>>> X[4]   # Raises exception!
...
IndexError: tuple index out of range

Concatenation of tuples:

>>> X + Y
(24, 3.1400000000000001, 'w', 7, 100)

To compute the length of a tuple, do:

>>> len(X)

4

3.4.3.3. Tuples versus lists

In every way we’ve thus far discussed, tuples are like lists.

But there is one crucial difference. Tuples do not allow assignments:

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

This is because tuples, like strings, are not mutable. Mutable types can be updated. Immutable ones cannot. Lists and dictionaries are mutable. Tuples and strings are not. Mutable types take less space and are the appropriate types for data that does not need to be updated. But in many cases, updating is necessary. In that case, dictionaries and tuples are needed.

3.4.3.4. Tuples operators and methods

In the following examples, T is a list. There are fewer tuple methods than list methods, because tuples cannot be altered once created.

len(T)

Returns length of tuple T.

x in T

Returns True if x is in T. Otherwise returns False.