Home      |       Contents       |       About

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

The 'tuple' object


  • 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
(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
(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'
([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')

L = list('spamspam')
t = tuple(L)
('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'
['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)
(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'}

. Free learning material
. See full copyright and disclaimer notice