11d. Additions: Tuples Are Immutable#

Additions to Chapter 11: Tuples: what it means that tuples are immutable (“But tuples are immutable” in Chapter 11), shown with two variables that refer to the same tuple, a copy, and state diagrams. Read this page after the chapter. The practice questions at the end have answers: try each question first, then open its Answer.

Run this page on Colab

Run the setup cell below first. It downloads thinkpython.py, which lets this page show the errors of some examples without stopping the page, and diagram.py and yrdiagram.py, which draw the state diagrams.

from os.path import basename, exists

def download(url):
    filename = basename(url)
    if not exists(filename):
        from urllib.request import urlretrieve

        local, _ = urlretrieve(url, filename)
        print("Downloaded " + str(local))
    return filename

download('https://github.com/AllenDowney/ThinkPython/raw/v3/thinkpython.py');
download('https://github.com/AllenDowney/ThinkPython/raw/v3/diagram.py');
download('https://y-rosenthal.github.io/yrThinkPython/yrdiagram.py');

import thinkpython

y = x and a copy#

A tuple is a sequence like a list, but a program cannot change a tuple after it makes it. Make a tuple x, a second variable y with y = x, and a third variable z with z = tuple(x). For a list, list(x) makes a copy (Chapter 9). tuple(x) is the same idea for a tuple. The is operator tells whether two variables refer to the same object (“Objects and values” in Chapter 9):

x = ('red', 'green', 'blue')
y = x
z = tuple(x)
print(x is y, x is z)
True True

Both are True: x, y and z refer to one tuple. y = x does not make a new tuple. And tuple(x) does not make a copy either: it returns the same tuple, because a tuple cannot change, so a copy would never be useful. The state diagram shows it:

../_images/580ffe556c581bafee405b2fe1bed89d4fa2c65fbcbf4b8b15a28d8756abaa77.png

How to read the diagram. It uses the notation of the book’s state diagrams and stack diagrams (Chapters 2, 3 and 9). The gray box on the left is the frame __main__: it holds the variables. Each arrow goes from a variable to the object that it refers to. Two arrows that end at the same object mean that the two variables refer to the same object. The diagram is drawn from the real variables: it runs the code above, and uses is to find which variables refer to the same object.

Changing a tuple through y: not possible#

A tuple has no method that changes it (no append, no remove), and an assignment to an item is an error:

x = ('red', 'green', 'blue')
y = x
y[0] = 'pink'
TypeError: 'tuple' object does not support item assignment

The only thing that a program can do with y is to assign a new tuple to it. y + ('black',) makes a new tuple, and the assignment makes y refer to it. (('black',) is a tuple with one item: Chapter 11 explains the comma.) x and z still refer to the old tuple:

x = ('red', 'green', 'blue')
y = x
z = tuple(x)
y = y + ('black',)
print('x:', x)
print('y:', y)
print('z:', z)
x: ('red', 'green', 'blue')
y: ('red', 'green', 'blue', 'black')
z: ('red', 'green', 'blue')
../_images/3b29861508666d844a3483ec854c4194f622b0be13ccee3e56ad23692d4cd85a.png

The tuple ('red', 'green', 'blue') did not change: no program can change it. So a change “through y” can never affect x or z.

Compare with a list. With a list, the same steps give a different result: y.append('black') changes the one list that x and y refer to, so x shows the change, and only the copy z does not (“9b. Additions: Iterables, and Changing a List in a Loop”, “Lists are mutable”):

x = ['red', 'green', 'blue']
y = x
z = list(x)
y.append('black')
print('x:', x)
print('y:', y)
print('z:', z)
x: ['red', 'green', 'blue', 'black']
y: ['red', 'green', 'blue', 'black']
z: ['red', 'green', 'blue']
../_images/35fe32e02e05cea01ef3d6ad1f2fca33091a78f266dd1968a775192b9f49653a.png

y = x

a copy: z = tuple(x), z = list(x)

y changes

tuple (immutable)

y refers to the same tuple

z refers to the same tuple (no copy is needed)

not possible: y = ... makes y refer to a new tuple, and x and z do not change

list (mutable)

y refers to the same list

z refers to a new list

x shows the change, z does not

This is one reason to use a tuple: when a function gets a tuple, it cannot change it, so the caller’s values are safe.

Practice questions#

Question 1 (easy): what is displayed?#

Predict what this code displays. Then run the cell to check (on the website, click Show code cell output).

point = (3, 4)
other = point
copy = tuple(point)
print(point is other, point is copy, point == copy)

Hide code cell output

True True True

Question 2 (medium): what is displayed?#

Predict what this code displays. Then run the cell to check (on the website, click Show code cell output).

a = (10, 20)
b = a
b = b + (30,)
c = [10, 20]
d = c
d.append(30)
print(a, b)
print(c, d)

Hide code cell output

(10, 20) (10, 20, 30)
[10, 20, 30] [10, 20, 30]

Question 3 (medium): which lines cause an error?#

t = ('a', 'b', 'c'). Which of these lines cause an error? For each line that works, what is t after it?

  1. t[1] = 'x'

  2. t = t + ('d',)

  3. t.append('d')

  4. t = ('z',) + t[1:]

Question 4 (hard): write a function#

Write a function called replace_first that takes a tuple and a value, and returns a new tuple that is the same as the tuple, but with the value as its first item. For example, replace_first(('a', 'b', 'c'), 'z') returns ('z', 'b', 'c'). For an empty tuple, the function returns the empty tuple: replace_first((), 'z') returns ().

Start from this header (replace ... with the body):

def replace_first(t, value):
    ...

Credits#

Additions by Prof. Y. Rosenthal, for Think Python: 3rd Edition by Allen B. Downey. Text license: Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International