+ 1
can anyone help me understanding this python multidimensional array problem.
x = [[0]*2]*2 x[0][0]=1 then if i print x,why does it shows [[1,0],[1,0]] instead of [[1,0],[0,0]]
3 ответов
+ 1
When you create a list with *, you effectively add REFERENCE to the list and not copies. At example:
l= [0,0]*2
# now l will be [[0,0],[0,0]
# but either items are SAME
# object then if you modify one
# then other one will be modified
# also
l[0][0]= 1
# At thid point you edits
# first item of first item of
# l BUT because it contains
# two items that ARE SAME OBJECT
# you will edit also the first
# item of second item of
# l
In practice when you do
l= [i1,i2 ... im]*n
its almost like
tmp= [i1, i2 .... im]
l= [tmp, tmp ... tmp] # n times
0
Are you sure that the code and the output is like you writed?
0
my mistake,edited to complete problem