+ 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]]

24th Oct 2018, 4:41 PM
Aamirsohel khan
Aamirsohel khan - avatar
3 Respostas
+ 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
24th Oct 2018, 5:48 PM
KrOW
KrOW - avatar
0
Are you sure that the code and the output is like you writed?
24th Oct 2018, 4:53 PM
KrOW
KrOW - avatar
0
my mistake,edited to complete problem
24th Oct 2018, 4:58 PM
Aamirsohel khan
Aamirsohel khan - avatar