Tuples

Similar to a list, a tuple is an object that contains multiple data items. However, these items are "immutable" - which means they CANNOT be changed during a program's execution. In Python, we write tuples with round brackets (paratheses).

info

Note the >>> prompt in the examples below indicates that they are running in the PYTHON shell using the "interactive" mode.

Creating a tuple.

>>>thistuple = ("apple", "banana", "cherry")
>>>print(thistuple)
('apple', 'banana', 'cherry')

You can access tuple items by referring to the index number, inside square brackets, similar to how you would access items in a list.

>>>thistuple = ("apple", "banana", "cherry")
>>>print(thistuple[1])
banana

You can specify a range of indexes similar to what you do with lists.

When specifying a range, the return value will be a new tuple with the specified items.

>>>thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
>>>print(thistuple[2:5])
('cherry', 'orange', 'kiwi')

Keep in mind tuples are immutable or unchangeable. So you cannot change its values once it's created.

>>>x = ("apple", "banana", "cherry")
>>>x[1] = "kiwi"
Traceback (most recent call last):
  File "", line 1, in
    x[1] = "kiwi"
TypeError: 'tuple' object does not support item assignment

You can, however, convert a tuple into a list using the list() function, modify the values, then convert it back into a tuple using the tuple() function.

>>>x = ("apple", "banana", "cherry")
>>>y = list(x)
>>>y[1] = "kiwi"
>>>x = tuple(y) >>>print(x) ('apple', 'kiwi', 'cherry')

Further Reading