$$ \newcommand{\tp}{\thinspace .} $$

This chapter is taken from the book A Primer on Scientific Programming with Python by H. P. Langtangen, 5th edition, Springer, 2016.


Tuples are very similar to lists, but tuples cannot be changed. That is, a tuple can be viewed as a constant list. While lists employ square brackets, tuples are written with standard parentheses:

>>> t = (2, 4, 6, 'temp.pdf')    # define a tuple with name t
One can also drop the parentheses in many occasions:

>>> t = 2, 4, 6, 'temp.pdf'
>>> for element in 'myfile.txt', 'yourfile.txt', 'herfile.txt':
...     print element,
myfile.txt yourfile.txt herfile.txt
The for loop here is over a tuple, because a comma separated sequence of objects, even without enclosing parentheses, becomes a tuple. Note the trailing comma in the print statement. This comma suppresses the final newline that the print command automatically adds to the output string. This is the way to make several print statements build up one line of output.

Much functionality for lists is also available for tuples, for example:

>>> t = t + (-1.0, -2.0)           # add two tuples
>>> t
(2, 4, 6, 'temp.pdf', -1.0, -2.0)
>>> t[1]                           # indexing
>>> t[2:]                          # subtuple/slice
(6, 'temp.pdf', -1.0, -2.0)
>>> 6 in t                         # membership
Any list operation that changes the list will not work for tuples:

>>> t[1] = -1
TypeError: object does not support item assignment

>>> t.append(0)
AttributeError: 'tuple' object has no attribute 'append'

>>> del t[1]
TypeError: object doesn't support item deletion
Some list methods, like index, are not available for tuples. So why do we need tuples when lists can do more than tuples? There is also a fourth argument, which is important for a data type called dictionaries: tuples can be used as keys in dictionaries while lists can not.