Changing the same element in all lists in a 2D-array

Question:

When doing something like for example:

arr = [[0]*3]*3
arr[1][0] = 4

It will alter the first element in all three lists. Is this because we are only making a copy of the first list and the elements share the same pointer in memory?

That is, the first list is for example:

[A,A+C,A+2C] where C is the Offset and A is the address to the first value.
And the construction above creates a list:
[[A,A+C,A+2C], [A,A+C,A+2C], [A,A+C,A+2C]]
Ergo, if we change any element in any position of one of the lists, we alter the corresponding the the other lists?

Asked By: Randy

||

Answers:

Exactly. The repeat command *3 Makes a shallow copy, in all instances. Something to watch out for. I personally have been bitten by this in initialization, e.g.

a, b = []*2

Makes a and b refer to the same object.

Answered By: Yuri Feldman
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.