+ 7
Task in the challenge
Hi everyone! Can anybody help me with a task from challenge? Explain me, please, !!WHY!! it works as it works? Why list 'a' not the same thing as 'b' in my code bellow??? https://code.sololearn.com/cCg4x5xaGe70/?ref=app
4 Answers
+ 14
first case the list a=[1,1] is doubled and then the first element is replaced by 2
second case is the list b which has 2 lists inside it. So when you put b[0][0]=2, only the first element of first list is assigned the value 2.
i hope the explanation is sufficient to explain how it works
+ 12
what I understand is that these expressions will produce same result.
[[1]*2]*2 == [[1,1]]*2
+ 2
@Umesh Thanks for answer, but I still not understand.
Now I try to change expression
a[0][0] = 2
to
a[0] = 2
it's obvious that 'print(a)' become: [2, [0,0]]
Please, tell me if I understand right:
when I do "a = [[1,1]] * 2" it mean that duplicate creates not like a copy, but like a reference?
+ 2
yes, I've tried it too. And also I've tried a[0][1]=2 and result of it was [[1,2][1,2]]. But this does not simplify the situation((