Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this kind of array mean/do? [duplicate]

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
like image 985
Alias Avatar asked Dec 28 '25 17:12

Alias


1 Answers

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.

like image 63
Christian Tapia Avatar answered Dec 31 '25 07:12

Christian Tapia