There are two examples, the first one is as follows,
a=[0]*5
for i in range(5):
a[0]=i+3
At this time, a=[3,4,5,6,7]
The second one is as follows:
a=[[0,0]]*5
for i in range(5):
a[0]=i+3
At this time, a=[[7, 0], [7, 0], [7, 0], [7, 0], [7, 0]]
Why does this happen? Is there anything wrong with my second way of writing?
Newbies, please give me some advice!
You have made two problems here:
The first one, as mentioned above, you have been modifying the value of a[0], and you have not put the changed
i
into the list for processing, or in other words, You missed the code to writei
into the question:Correct method:
The second question, which is what you asked above, is why
a=[[0,0]]*5
This definition method turns out to bea=[[7, 0], [7 , 0], [7, 0], [7, 0], [7, 0]]
This question has one thing in common with the first question, that is, you probably forgot to write
a[i][ 0] = i + 3
,The second is: If you use
[[0, 0]] * 5
to generate a list, everything in it is a reference, they are the same object, not 5 Object! See example:You can see from the
id
value that they all have the same address, so the 5 objects in the list are all the same, so when you executea[i][0]= i+3
, no matter No matter which element you modify, you will end up modifying the same list!So if you want to try the effect you want, you can’t use that method to quickly generate a list, you can only use the following method:
Because you need to use the i variable to iterate, if you always change 0, a[0] will of course be overwritten, and it will be the last value
In the first code, you cannot get a=[3,4,5, 6,7], you have to use the i variable
Second code:
It seems that you wrote the code wrong, I guess you want to ask this question
You can print out a
@Lin_R is right
In fact, the second method is shared, not separate. Because it is a list at this time and is variable, while the first method is a number and is immutable.