I found this declaration in a piece of code involved in a puzzle, could anyone explain what it's doing? I've tried looking myself but I don't really understand.
test = [[0] * 9] * 9
I found this declaration in a piece of code involved in a puzzle, could anyone explain what it's doing? I've tried looking myself but I don't really understand.
test = [[0] * 9] * 9
When you do
[0] * 9
you get a list
with nine 0
's:
[0, 0, 0, 0, 0, 0, 0, 0, 0]
When you do
[[0] * 9] * 9
you get
[[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]]
In other words, you get [0, 0, 0, 0, 0, 0, 0, 0, 0]
9 times. But you have to be careful because this last, makes a shallow copy of the list. If you modify one element of that list, then it will be "modified" in all the lists (in fact because all those elements are the same list). If you want each list to be a different one, you could make a deep copy.
You can easily see this by using a print statement:
test = [[0] * 9] * 9
test[0][1] = 2
print test
>>> [[0, 2, 0, 0, 0, 0, 0, 0, 0], [0, 2, 0, 0, 0, 0, 0, 0, 0], [0, 2, 0, 0, 0, 0, 0, 0, 0], [0, 2, 0, 0, 0, 0, 0, 0, 0], [0, 2, 0, 0, 0, 0, 0, 0, 0], [0, 2, 0, 0, 0, 0, 0, 0, 0], [0, 2, 0, 0, 0, 0, 0, 0, 0], [0, 2, 0, 0, 0, 0, 0, 0, 0], [0, 2, 0, 0, 0, 0, 0, 0, 0]]
Note: List is a better name for [...]
in Python. Read more about lists and tuples.
Note: That is wrong. Don't use that as boilerplate code.
When you do
print [0] * 9
you get
[0, 0, 0, 0, 0, 0, 0, 0, 0]
The same element in the original array is referenced by all the nine elements in the new array. So, all of them print 0
. The same way, when you say
print [[0] * 9] * 9
it creates a list of 9 zeros (think of this as l1
) and then another list of 9 elements, all of which refer to the same list (l1
). So, when you change one element in the newly created list, change will be reflected in all the lists.
The proper way to do this would be
print [[0 for j in xrange(9)] for i in xrange(9)]
Since, integers are immutables in Python, you can write the same as
print [[0] * 9 for i in xrange(9)]
The syntax [0] * 9
will generate a list of 9 zeroes. So I believe the full code will generate a list of 9 lists of 9 zeroes.