3.4.3. Tuples 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

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. 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
>>> X[1]   # 2nd element
>>> X[-1]   # last element

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

>>> 24 in X
>>> 6 in X

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 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. 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.


Returns length of tuple T.

x in T

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