Reputation: 5106
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?
Upvotes: 1
Views: 570
Reputation: 308111
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.
Upvotes: 2
Reputation: 798526
Because you have 11 references to the same list.
G = [[0] * 11 for x in range(11)]
Upvotes: 4