0

I'm trying to initialize an empty list as [[], []] and then append to it. However, I am getting unexpected results with the following method vs another. What is going on under the hood in this scenario?

y = [[]] * 2
print(y)
y[0].append(1)
y[1].append(2)
print(y)

output:

[[],[]]
[[1,2], [1,2]]

While this following code gives me the intended results that I want.

x = [[], []]
print(x)
x[0].append(1)
x[1].append(2)
print(x)

output:

[[],[]]
[[1], [2]]
  • I'd say most likely when you use `[value] * 2`, the value gets copied, whether it's a value or a reference. – Captain Trojan Dec 10 '20 at 17:51
  • 2
    Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – ssp Dec 10 '20 at 17:51
  • @Moosefeather That does answer my question, thank you. – Levithan6785 Dec 10 '20 at 19:05

0 Answers0