1

I asked a question about initializing a 2 dimensional array yesterday, this is the link: How to implement this C++ source in python?

There is a problem in the answer, a friend mentioned a way:

G = [[0]*11]*11

But in this way, when I change the G[0][0] to 2, all the G[i][0](0<=i<11) will all change to 2, but I don't know why?

Supplement:

This is what I thought: The 0 or other number is immutable, so we change one of them, the others will not be changed. But the list [0, 0 ,0 ,.....] is mutable, so when we [0, 0, ...] * 11, all the [0, 0, ...] list will be the same, as is function is True. am I right?

2 Answers 2

4

Because you have 11 references to the same list.

G = [[0] * 11 for x in range(11)]
Sign up to request clarification or add additional context in comments.

Comments

2

The *11 notation makes 11 references to the same object. If the object is immutable you don't notice, because any attempt to change it changes the reference to a different object. When the object is mutable you can modify it, like assigning to a member of a list; since all the references are to the same object, all of them get modified at the same time.

Mutable/immutable might seem to change things, but it doesn't - Python is being consistent in both cases. Consider this example:

G[0] = [3]*11

You'll see that G[1] has not changed.

1 Comment

sorry, I don't know"Mutable/immutable might seem to change things, but it doesn't - Python is being consistent in both cases" this means? why"since all the references are to the same object, all of them get modified at the same time"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.