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:
One can also drop the parentheses in many occasions:
>>> t = (2, 4, 6, 'temp.pdf') # define a tuple with name t
>>> t = 2, 4, 6, 'temp.pdf' >>> for element in 'myfile.txt', 'yourfile.txt', 'herfile.txt': ... print element, ... myfile.txt yourfile.txt herfile.txt
forloop 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
Much functionality for lists is also available for tuples, for example:
Any list operation that changes the list will not work for tuples:
>>> t = t + (-1.0, -2.0) # add two tuples >>> t (2, 4, 6, 'temp.pdf', -1.0, -2.0) >>> t # indexing 4 >>> t[2:] # subtuple/slice (6, 'temp.pdf', -1.0, -2.0) >>> 6 in t # membership True
Some list methods, like
>>> t = -1 ... TypeError: object does not support item assignment >>> t.append(0) ... AttributeError: 'tuple' object has no attribute 'append' >>> del t ... TypeError: object doesn't support item deletion
index, are not available for tuples. So why do we need tuples when lists can do more than tuples?