-2

I am trying to edit elements in my list of list of list but it is editing multiple elements.

    L1 = [[0,0] for count in range(2)]
    L2 = [L1 for count in range(2)]
    L2[0][0][0] = 5
    print(L2)

What I expect is [[[5, 0], [0, 0]], [[0, 0], [0, 0]]]

But what I get is [[[5, 0], [0, 0]], [[5, 0], [0, 0]]]

It seems that I am editing the original list. Can someone explain how to edit a single element or set up nested lists where this effect won't occur.

Many thanks

1 Answers1

1

Don't reuse the variable:

L2 = [[[0,0] for count in range(2)] for count in range(2)]

Then the inner part [[0,0] for count in range(2)] will get recreated every time as a fresh, separate list.

Alex Hall
  • 34,833
  • 5
  • 57
  • 89