Home > database >  Python: Nested List is not replacing values correctly
Python: Nested List is not replacing values correctly

Time:10-13

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?

CodePudding user response:

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]
  • Related