-1
li = [1,2]
l = []
l.append(li)
li[0] = 2
li[1] = 3
l.append(li)
print(*l)

I expect it should print [[1,2],[2,3]], but it print [[2,3], [2,3]]. Can someone explain why? And if I want [[1,2],[2,3]], what should I do?

thank you

Matthew
  • 9
  • 2
  • Because `l` has two references *to the same list*, so of course, both those indices will show the same thing. Why would you *expect* it to work any other way? Why did you assume that `list.append` would create a copy of the argument? If you want that result, *you need to provide a copy* – juanpa.arrivillaga May 17 '22 at 03:05

0 Answers0