Tuples are collections of objects which are ordered and immutable. Tuples are classified as sequences like lists. The main difference is that cannot be changed, while lists can be changed. Create a list using square brackets and to create a tuple use parenthesis.
# create a list and a tuple
myList = [1, 2, 3]
myTuple = (1, 2, 3)
An empty tuple can be created by writing empty parentheses.
# create an empty tuple
myEmptyTuple = ()
Python indicates the type of the created object by empty parentheses. Therefore a tuple has been created.
To access the tuple values, we can use square brackets with the index of the element. It is possible to slice indices to return a range of elements. For example [0:2] returns the first two elements.
# access tuples
myTuple = ('zero', 'one', 'two', 'three')
print('first tuple value: ' + str(myTuple))
print('first two tuple values: ' + str(myTuple[0:2]))
first tuple value: zero
first three tuple values: ('zero', 'one')
Tuples are immutable, therefore we can not update values like in lists. It is possible to create a new Tuple for example by combining two tuples.
# combining tuples
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
tuple3 = tuple1 + tuple2
The new tuple3 has the combined values of tuple1 and tuple2.
(1, 2, 3, 4, 5, 6)
Tuples are immutable, therefore it's not possible to delete tuple values. It is possible to delete the whole Tuple with the del() function.
# delete tuple
myTuple = (1, 2, 3)
The print function cannot print the deleted tuple, an NameError exception is raised because the tuple doesn't exist anymore.
NameError: name 'myTuple' is not defined
Built-in functions for tuples
The table shows the built-in Python functions which can be used with tuples.
||count the length of the tuple
||returns the element with the highest value from the tuple
||returns the element with the lowest value from the tuple
||converts the tuple into a list (useful to make it mutable)
Methods of Tuples
There are 2 Tuple methods in Python. The table shows the available tuple methods count() and index().
||returns the count for a given element
||returns the index for a given element