0

I have a nested list containing nothing but 0's, defined by a size of 5 by 5, and I want to be able to set specific values int he nested list to 1 using direct indexing. This is the solution I currently have:

    Grid = [[0] * 5] * 5

    ObX = 2
    print(ObX)

    ObY = 3
    print(ObY)

    Grid[ObY][ObX] = 1
    print(Grid)

Expected output:

2

3

[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0]]

Actual Output:

2

3

[[0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0]]

As far as I can tell, it's ignoring the "ObY" index and just deciding that it wants to replace every value in each list at index "ObX". What am I doing wrong?

  • 1
    Does this answer your question? [List changes unexpectedly after assignment. Why is this and how can I prevent it?](https://stackoverflow.com/questions/2612802/list-changes-unexpectedly-after-assignment-why-is-this-and-how-can-i-prevent-it) – Chris Oct 13 '21 at 12:55

1 Answers1

2

The list of lists you created contains the same list 5 times, changing it once changes all of its copies

In [1]: Grid = [[0] * 5] * 5

In [2]: [id(x) for x in Grid]
Out[2]:
[140392398718848,
 140392398718848,
 140392398718848,
 140392398718848,
 140392398718848]

Use this to create 5 different lists

In [5]: Grid =[[0]*5 for _ in range(5)]


In [6]: [id(x) for x in Grid]
Out[6]:
[140392397938112,
 140392396267776,
 140392397478656,
 140392398276224,
 140392398427200]
Ron Serruya
  • 3,988
  • 1
  • 16
  • 26