Getting familiar in working with a Python tuple

By Abhinash & Priya Chetty on September 13, 2022

A Python tuple is a collection of immutable Python heterogeneous objects, where each of the values is separated by a comma and the entire collection is enclosed between curve brackets. Just like Python lists, tuples are indexed by their positions as indices.

A Python list is mutable while a Python tuple is immutable

The major difference between a tuple and a list is that a tuple is immutable, whereas a list is mutable. This means that once a tuple is created, it cannot be changed or updated like lists.

list = [1,2,3,4]
[1, 2, 3, 4, 5]
tuple = 1,2,3,4
AttributeError: 'tuple' object has no attribute 'append'

To change the elements of a tuple the variable containing a tuple needs to be reassigned. Similarly many list functions that aim to change the list and not make a new list do not work with tuples. Hence, lists are a mutable collection of objects while tuples are an immutable collection of objects.

tuple = 1,2,3,4,5

If a tuple contains a mutable object like lists, then the list in the tuple can be changed but the tuple cannot be changed.

Tuples, once created can also be integrated into Dictionaries, although lists cannot be. This is because Dictionaries allow only immutable objects, and since tuples are immutable. When the collection of objects is heterogeneous, it is advantageous to create tuples, instead of lists, since tuples are serially structured.

Concatenating Python tuples

Adding tuples

Although tuples are immutable and cannot be concatenated like lists but two tuples can be added to get a new tuple that will consist of all the objects of the tuples being added.

t1 = 'a','b','c','d'
t2 = 1,2,3,4
('a', 'b', 'c', 'd', 1, 2, 3, 4)

Repeating the occurrence of a tuple object

Like a list, a tuple can consist of multiple occurrences of the same object. To repeat the same object in a tuple simply multiply it by the number of occurrences required.

r = ('tuple',)*5
('tuple', 'tuple', 'tuple', 'tuple', 'tuple')

Slicing a Python tuple

Slicing literally means precisely cutting an object into smaller pieces. These smaller objects can have different purposes in an algorithm. Just like lists & strings a tuple can also be sliced by its index.

earth = 'plants', 'animals', 'birds', 'rocks', 'water', 'air'
living = earth[:3]
nonliving = earth[3:]
withlegs = earth[1:3]
visible = earth[:-1]
reverse = earth[::-1]

('plants', 'animals', 'birds')
('rocks', 'water', 'air')
('animals', 'birds')
('plants', 'animals', 'birds', 'rocks', 'water')
('air', 'water', 'rocks', 'birds', 'animals', 'plants')

Extracting the elements of a Python tuple to variables

Extracting all of the objects to multiple unique variables is easy in Python.

earth = 'plants', 'animals', 'birds', 'rocks', 'water', 'air'
a,b,c,d,e,f = earth
*a,b,c,d = earth

birds air
['plants', 'animals', 'birds'] water air