Tuples

Definition of tuples

Tuples are immutable objects that represent ordered sequences of other objects, which can be of any data type (including data structures).
Tuples can be created by assignment using ( ), inside of which we define tuple elements. Elements are separated with , . If the tuple consists of a single element, the comma ( , ) is necessary.
A tuple can also be created using the command (constructor) tuple(), inside of which we define the tuple elements.
Empty tuples are created with () or tuple().
>>> mj = ('Michael', 'Jordan', 'MVP', 'GOAT')
>>> print(mj)
('Michael', 'Jordan', 'MVP', 'GOAT')

>>> sport = tuple('football', 'volleyball', 'tennis')
>>> print(sport)
('football', 'volleyball', 'tennis')

>>> one_el = ('X',)
>>> print(one_el)
('X',)

Accessing tuple elements

We can perform slicing with tuples in the same way as with lists. However, the elements inside the tuple cannot be changed in the process. To overcome this, we can create another tuple by slicing an existing tuple.

>>> t1 = (1, 2, 3, 4, 5)
>>> t1[1] = 5
TypeError: 'tuple' object does not support item assignment

>>> t2 = t1[1:4]
>>> print(t2)
(2, 3, 4)

Management of tuple elements

Tuples are immutable objects, which means values of tuple elements cannot be changed nor deleted after a tuple is created. However, we can add new elements to the end of the tuple by concatenation (addition or add-and-assign), or multiply the tuple by an integer, increasing the number of elements, not values (see the example).

>>> tup = ('x', 'y', 'z')
>>> tup += ('p', 'q') #adding new values to the end of the tuple
>>> print(tup)
('x', 'y', 'z', 'p', 'q')

>>> print(tup*2) #multipying the tuple by 2 gives us twice as many elements
('x', 'y', 'z', 'p', 'q', 'x', 'y', 'z', 'p', 'q')

>>> tup[1] = 'YY' #changing values of elements in the tuple is not allowed
TypeError: 'tuple' object does not support item assignment

>>> del(tup[2]) #we cannot delete elements in the tuple
TypeError: 'tuple' object doesn't support item deletion

>>> del(tup) #this is ok

Iteration and membership

Iteration through a tuple is done using a for-loop. Membership to a tuple can be tested with the membership operators in or not in, which return True if an element belongs to the tuple, otherwise they return False.

>>> letters = ('a', 'b', 'c', 'd')
>>> char = 'w'
>>> char in letters

False

>>> for i in letters:
        print(i)

a
b
c
d

Table of contents

Leave a Reply