When hand holding goes wrong

Assignment by reference vs copy assignment

In case you accept doing assignment at all in your language you need to choose which way to pass your objects when assigning to new variables or calling functions etc. There are two general ways; You either copy it or just tell where the original is. We could imagine some combination of these if parts of the object is heavy to copy but let’s keep it in our pants.

In a reasonable language like c++ you get to choose. In Python you need to understand the wicked minds of the language creators.

The other day I found an example where you lose your will to live.

The example

If you want to generate for example a truth table or a matrix with some ones and zeros of a fixed size you might want to create lists of a fixed size and then reassign the values in certain positions in these lists. A Pythonic way of writing this would be

size_of_list = 5
my_list = [0] * size_of_list

This works great! You get a list just the size you want it and it contains the right amount of zeros. If you change the entry at an index using brackets you get the results you would expect.

Now what happens if you want a list of lists, a matrix! You might as I was be tempted to simply write:

from pprint import pprint
x = [[0] * 5] * 5
x[0][0] = 1
pprint(x)
$ python test.py
[[1, 0, 0, 0, 0],
 [1, 0, 0, 0, 0],
 [1, 0, 0, 0, 0],
 [1, 0, 0, 0, 0],
 [1, 0, 0, 0, 0]]

This unfortunately does not only change the entry [0][0] but all the entries in column 0? Why? Because every list object in python is passed by reference. When we make 5 of [[0] * 5] we are no longer making 5 primitive objects into a list we are creating 5 references to the same mutable list object.

So what?

Python is marketed as being intuitive. Beautiful is better than ugly. Simple is better than complex, complex is better than complicated. I have asked a handful of people what they think this code will produce. Each with a university education either in or related to computer science and each of them got it wrong on the first go, even with a lot of winks and discussing assignment before.