Mutability misconceptions
What is an assignment?
This is an assignment statement:
>>> a = 3
We’re using the = sign to assign a variable to a value.
Note that assignment doesn’t only happen with an = sign.
A for loop also performs an assignment:
>>> numbers = [1, 2, 3]
>>> for x in numbers:
... print("x is now:", x)
...
x is now: 1
x is now: 2
x is now: 3
>>> x
3
Also note that defining a function will assign to the variable name for that function:
>>> def double(number):
... return number * 2
...
>>> double
<function double at 0x...>
We now have a variable that points to a function object. Yes, functions are objects in Python (more on that later).
And creating a class will assign a variable that points to a class object:
>>> test = "This is a test"
>>> test
'This is a test'
>>> class test:
... pass
...
>>> test
<class 'test'>
(Yes classes are objects in Python also!)
Also the import statement will assign to the variable for that module name:
>>> math = "fun"
>>> math
'fun'
>>> import math
>>> math
<module 'math' (built-in)>
And the from syntax for the import statement assigns to one or more variables as well:
>>> from math import sqrt, cos
>>> cos
<built-in function cos>
>>> sqrt
<built-in function sqrt>
Function calls also perform assignments. When we call a function, we assign to the names for those function arguments:
>>> def f(x):
... print("x is", x)
...
>>> f(5)
x is 5
We’re going to talk about assignment from the perspective of the assignment statement. But keep in mind that everything we’re about to see about assignment also applies to all other forms of assignment.
Variables are not buckets
Is Python pass-by-reference or pass-by-assignment?
This question has a built-in assumption that variables in Python are buckets that contain objects and that assignment statements copy objects. None of that applies to Python.
Let’s take a look at how Python’s variables and objects actually work. We’re going to quiz ourselves to see what we understand and what we don’t.
We have a variable a that points to a list:
>>> a = [2, 1, 3, 4]
Let’s make a new variable b by assigning b to a:
>>> b = a
If we append a new item to b, what will its length be?
>>> b.append(7)
>>> len(b)
Initially the b list had 4 items and now it should have 5:
>>> len(b)
5
How many items does a have?
>>> len(a)
What’s your guess?
Is it 5?
Or is it still 4?
The a list also has 5 items:
>>> len(a)
5
What’s going on here?
Well, the variables a and b both point to the same list!
If we look up the unique ID for the object that each of these variables points to, we’ll see that they both point to the same object:
>>> id(a)
140139323640128
>>> id(b)
140139323640128
This is possible because variables in Python are not buckets but pointers.
Let’s say we’ve made three assignments to three variables (a, b, and c):
>>> a = [2, 1, 3, 4]
>>> b = a
>>> c = [2, 1, 3, 4]
This is how Python represents these variables and objects:
┏━━━━━━━━━━━┓
┃ Variables ┃ ┏━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┓
┡━━━━━━━━━━━┩ ┃ Object ID ┃ Object Value ┃
│ a │━━━━━┓ ┡━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━┩
│ b │━━━━━┻━━━━►│ 140201481803816 │ [2, 1, 3, 4] │
│ c │━━━━━━━━━━►│ 140201481803848 │ [2, 1, 3, 4] │
└───────────┘ └─────────────────┴──────────────┘
Note that all of the variables are in one location and all the objects are stored somewhere else.
At any given time, each variable in Python points to exactly one object. But each object may have multiple variables pointing to it.
In our case, the variables a and b both point to the same object!
Assignments versus mutations
Currently a and b both point to the same object:
>>> a
[2, 1, 3, 4]
>>> b
[2, 1, 3, 4]
>>> a is b
True
Let’s say we change the value of b with an assignment statement:
>>> b = [3, 5, 6]
There are now only 3 items in b:
>>> len(b)
3
How many items are in a?
>>> len(a)
Is it still 4?
Or is it 3?
The list a still has 4 items:
>>> len(a)
4
The variables a and b originally pointed to the same list.
We assigned the variable b to a new object.
That didn’t affect a at all.
Our a variable still points to the original list.
Python has 2 distinct types of change:
Assignment changes a variable (it changes which object it points to)
Mutation changes an object (which any number of variables might point to)
Assignment changes a variable… that is, it changes which object a variable points to. Mutation changes an object… which any number of variables might point to.
Augmented assignments
We have two variables pointing to the same list:
>>> a = [2, 1, 3, 4, 7]
>>> b = a
What would happen if we used the += operator to add more items to the a list?
>>> a += [11, 18, 29]
This changes a:
>>> a
[2, 1, 3, 4, 7, 11, 18, 29]
Does it change b?
>>> b
It does!
>>> b
[2, 1, 3, 4, 7, 11, 18, 29]
The += operator is called an in-place addition.
It’s supposed to add to our list in-place.
An in-place addition operation is expected to mutate the list object that we’re using it on.
This type of assignment, where we’re doing some operation while we’re assigning, is called an augmented assignment statement
In-place addition is not the only augmented assignment statement.
Some of the other augmented assignments are in-place subtraction (-=), in-place multiplication (*=), and in-place division (/=).
All of these operators are expected to operate in-place, meaning they’re expected to mutate the object that our variable (numbers in our case) is pointing to.
An assignment statement does an assignment only, so this would not mutate the original list:
>>> a = a + [11, 18, 29]
But an augmented assignment statement does an assignment and a mutation, so this does mutate the original list:
>>> a += [11, 18, 29]
You might be thinking “wait, haven’t I seen += used on an immutable object?”
You probably have.
In Python, strings, numbers and tuples are all immutable, meaning we can’t change their value.
We have two variables (c and d) that both point to the same string:
>>> c = d = "Hello world"
If we take c and we use += on it:
>>> c += "!!"
It works:
>>> c
'Hello world!!'
Python doesn’t give us an error: it concatenates !! to our string.
But it didn’t actually change the string object.
The variable d (which pointed to the same string as c) is unchanged:
>>> d
'Hello world'
We did an assignment but not a mutation.
Whenever += is used on an object that is immutable (an object that can’t be changed) Python falls back to using that operator that we’re working with (+ in this case) and doing a regular assignment.
Meaning for immutable objects like tuples, strings, and numbers using += is the same as using = and + separately:
>>> c += "!!"
>>> c = c + "!!"
You can think of the += operator is being implemented a bit like this:
def in_place_add(our_object, other_object):
if not hasattr(our_object, "__iadd__"):
return our_object + other_object
return our_object.__iadd__(other_object)
So, with that function defined, these two lines are pretty much equivalent:
>>> some_object += something_else
>>> some_object.in_place_add(something_else)
Thinking about this further
The name to object mapping is similar to dictionaries.
In fact, looking at the local and global names using the locals and globals built-in functions will return a dictionary mapping the names in that scope to the objects they point to:
>>> locals()
>>> globals()
More thoughts on the way names and objects work:
Names point to objects, but objects don’t point to names
An object doesn’t know its names
In a sense, a name has an object but an object doesn’t have a name
Names and objects are a one-to-many relationship (one object per name in each scope, but many possible names per object)
Mutability Exercises
These exercises are all in the mutability.py file in the exercises directory. Edit the file to fix the error(s) in the function(s). To run the test: from the exercises folder, type python test.py <function_name>, like this:
$ python test.py swap_ends
Swap Ends
The following code is failing the tests. Figure out why the code is failing and then fix it:
def swap_ends(sequence):
"""Swap the first and last items in the given list."""
sequence = sequence[-1:] + sequence[1:-1] + sequence[:1]
It should work like this:
>>> from mutability import swap_ends
>>> numbers = [1, 2, 3, 4, 5]
>>> swap_ends(numbers)
>>> numbers
[5, 2, 3, 4, 1]
Rotate List
The following code is failing the tests. Figure out why the code is failing and then fix it:
def rotate_list(some_list):
"""Move first list item to end of list and return the item moved."""
some_list = some_list[1:] + some_list[:1]
return some_list[-1]
It should work like this:
>>> from mutability import rotate_list
>>> numbers = [1, 2, 3, 4, 5]
>>> rotate_list(numbers)
1
>>> numbers
[2, 3, 4, 5, 1]
>>>
Pop N
The following code is failing the tests. Figure out why the code is failing and then fix it:
def pop_n(sequence, n):
"""Remove and return the last n items from the mutable sequence."""
ret = sequence[-n:]
sequence = sequence[:-n]
return ret
It should work like this:
>>> from mutability import pop_n
>>> numbers = [1, 2, 3, 4, 5]
>>> pop_n(numbers, 2)
[4, 5]
>>> numbers
[1, 2, 3]
>>> pop_n(numbers, 0)
[]
>>> numbers
[1, 2, 3]
>>> pop_n(numbers, 3)
[1, 2, 3]
>>> numbers
[]
Sort Names
The following code is failing the tests. Figure out why the code is failing and then fix it:
def name_key(name):
"""Return last-first name tuple from first-last name string."""
first, last = name.split()
return last, first
def sort_names(names):
"""Return given first-last name strings sorted by last name."""
return names.sort(key=name_key)
The code should work like this:
>>> from mutability import sort_names
>>> names = ["Jill Moore", "Ben Sato", "Tanya Jackson", "Evelyn Moore"]
>>> sort_names(names)
['Tanya Jackson', 'Evelyn Moore', 'Jill Moore', 'Ben Sato']
Extended Swap Ends
Modify swap_ends to accept an optional argument n that will specify how many elements from the beginning and end should be swapped.
>>> from mutability import swap_ends
>>> numbers = [1, 2, 3, 4, 5]
>>> swap_ends(numbers, n=2)
>>> numbers
[5, 4, 3, 2, 1]
>>> numbers = [1, 2, 3, 4, 5, 6, 7]
>>> swap_ends(numbers, n=2)
>>> numbers
[7, 6, 3, 4, 5, 2, 1]
Note
To test this exercise you’ll need to comment out the @unittest.expectedFailure line in mutability_test.py.
Is Perfect Cube
The following code is failing the tests. Figure out why the code is failing and then fix it:
def is_perfect_cube(n):
"""Return True if the given number is a perfect cube."""
return round(n**(1/3)) ** 3 is n
It should work like this:
>>> from mutability import is_perfect_cube
>>> is_perfect_cube(64)
True
>>> is_perfect_cube(453)
False
>>> is_perfect_cube(2197) # 13**3
True
Identity
The following code is failing the tests. Figure out why the code is failing and then fix it:
def identity(int):
"""Return an identity matrix of size int x int"""
return [
[int(row == col) for row in range(int)]
for col in range(int)
]
It should work like this:
>>> from mutability import identity
>>> identity(2)
[[1, 0], [0, 1]]
>>> identity(3)
[[1, 0, 0], [0, 1, 0], [0, 0, 1]]
>>> identity(4)
[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]