Before you keep reading...
Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.
Before you keep reading...
Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.
10.27. Tuples and Mutability¶
So far you have seen two types of sequential collections: strings, which are made up of characters; and lists, which are made up of elements of any type. One of the differences we noted is that the elements of a list can be modified, but the characters in a string cannot. In other words, strings are immutable and lists are mutable.
A tuple, like a list, is a sequence of items of any type. Unlike lists, however, tuples are immutable. Syntactically, a tuple is a comma-separated sequence of values. Although it is not necessary, it is conventional to enclose tuples in parentheses:
julia = ("Julia", "Roberts", 1967, "Duplicity", 2009, "Actress", "Atlanta, Georgia")
Tuples are useful for representing what other languages often call records — some related information that belongs together, like your student record. There is no description of what each of these fields means, but we can guess. A tuple lets us “chunk” together related information and use it as a single thing.
Tuples support the same sequence operations as strings and lists. For example, the index operator selects an element from a tuple. A tuple can be the sequence in a for-loop.
As with strings, if we try to use item assignment to modify one of the elements of the tuple, we get an error.
julia = 'X' TypeError: 'tuple' object does not support item assignment
Of course, even if we can’t modify the elements of a tuple, we can make a variable
reference a new tuple holding different information. To construct the new tuple,
it is convenient that we can slice parts of the old tuple and join up the
bits to make the new tuple. So
julia has a new recent film, and we might want
to change her tuple. We can easily slice off the parts we want and concatenate them with
the new tuple.
To create a tuple with a single element (but you’re probably not likely
to do that too often), we have to include the final comma, because without
the final comma, Python treats the
(5) below as an integer in parentheses: