Prev: Dictionary functions and methods       |       Next: The 'set' object

# The 'tuple' object¶

## 'tuple'¶

• A tuple is a sequential structure similar to a list, but with one important difference: a tuple is immutable
• Practically this means that after defining a tuple, we can not change its items with assignments
In [1]:
t = (1,2,3)
t[0] = 'X'

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-1-4b3666acbd74> in <module>()
1 t = (1,2,3)
----> 2 t[0] = 'X'

TypeError: 'tuple' object does not support item assignment

#### Tuple features¶

• A tuple is:
• sequencial, heterogeneous, ordered: just like a list
• indexed: a tuple implements integer-based indices.
• When writing a tuple the values are enclosed in parentheses (or even without them as a comma-separated list of items)
• When accessing a tuple item the index is written in square brackets
• immutable: as explained above

#### To change a tuple...¶

• (a) Reconstruct it
In [10]:
t = (1,2,3,4)
#...............
t = 10,9,8,7
t

Out[10]:
(10, 9, 8, 7)
• (b) Use slices to construct a new object
In [6]:
t = (1,2,3,4)
t = t[:3]+(10,)   # Note the comma in (10,): denotes an one-item tuple
t

Out[6]:
(1, 2, 3, 10)
• (c) Change tuple implicitly: by changing the values in tuple items that are mutable objects themselves (for example, when lists are items of a tuple)
In [11]:
t = [100], [20, 30], 'str'
t[1][0] = 'X'
t

Out[11]:
([100], ['X', 30], 'str')

#### The 'tuple()' constructor¶

• As it happens with other object types, tuples are constructed by the tuple() constructor method, when passing a sequence as argument.
In [21]:
t = tuple('spam')
print(t)

L = list('spamspam')
t = tuple(L)
print(t)

('s', 'p', 'a', 'm')
('s', 'p', 'a', 'm', 's', 'p', 'a', 'm')


#### Tuple as iterable¶

...works just like a list with one subtle difference:

• A tuple iterable can not be assigned a different value in the loop (while a list iterable can). So, if you want to make sure that the iterable does not change during loop execution use tuple instead.
• The following code changes the list iterable values within the loop. This cannot be done if iterobj is a tuple.
In [23]:
iterobj = [1,2,3,4,5]

for i in iterobj:
if i%2:
iterobj[i-1] = 'ok'
print(iterobj)

['ok', 2, 'ok', 4, 'ok']


## Use tuple¶

• (a) To represent vector-like constant values: For example, in code handling graphics and web colors a common practice is to represent colors in RGB model as triplets
In [25]:
BLACK = (0,0,0)
WHITE = (255,255,255)
print(BLACK, WHITE)

(0, 0, 0) (255, 255, 255)

• (b) As dictionary keys: tuples are immutable and can be used as keys in a dictionary
In [27]:
di = {(0,0,0):'black', (255,255,255):'White'}
di[(0,0,0)]

Out[27]:
'black'

. Free learning material
. See full copyright and disclaimer notice