1

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?

1

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.