0

I am working with a list of lists in python and I came across a curious issue with it. For example, if I first create a list populated by placeholder [1,2,3] lists:

a = [[1,2,3]]*5

I would get the following result: a = [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]].

If I was to change a specific value of the inside list such as this:

a[1][2] = 5

I would get the following result: a = [[1, 2, 5], [1, 2, 5], [1, 2, 5], [1, 2, 5], [1, 2, 5]]. It looks like each of the index = 2 values of the inside list are not changed to my new variable. In this example all the variables are linked between the 5 inside lists. Now, if I was to create this list manually with the following command:

b = [[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3]]

And then repeat the assignment:

b[1][2] = 5

I would get the following result: b = [[1, 2, 3], [1, 2, 5], [1, 2, 3], [1, 2, 3], [1, 2, 3]]

It looks like in the case of list a, I have linked variables but in the case of list b, I do not. Could someone explain what is the reason for this? Is there any way to make list a behave like list b without creating a brand new list?

Any info would be greatly appreciated!

Thanks!

  • 1
    `a = [[1,2,3] for _ in range(5)]` basically the same list is ref-copied 5 times. – cs95 Oct 26 '17 at 15:12
  • try this and you will see why. `print(id(a[0]),id(a[1]), id(a[2]))` with output:`139846147583112 139846147583112 139846147583112` and `print(id(b[0]),id(b[1]), id(b[2]))` without: `139846147583176 139846147583240 139846147583432`. Think of id as a memory address for each of these sublists. – utengr Oct 26 '17 at 15:33

0 Answers0