0

I have an array within an array, and I can call its values just fine. However, whenever I try to change the value of something in the second array it changes it for all of the arrays in the first array.

for yAxis in range(len(g.WORLD)):
    if yAxis == yPos:
        yRay = g.WORLD[yAxis]
        print("=====")
        print(yAxis)
        print(yPos)
        print("====")
        for xAxis in range(len(yRay)):
            if xAxis == xPos:
                print("-------")
                print(xAxis)
                print(xPos)
                print(yRay)
                print("-------")
                yRay[xPos] = 1 

This does the same thing

 g.WORLD[yAxis][xAxis] = 1
user2653663
  • 2,818
  • 1
  • 18
  • 22
  • 1
    How are you creating the lists in the first place? Something like `[[]] * width`? – Carcigenicate Jan 21 '20 at 13:10
  • Would you perhaps define the objects that you are using and describe better your input / output / expected output (in other words: please provide a [minimal reproducible example](/help/mre)). Apparently, most people here assume you are using a Python `list`, but this is not explicitly indicated. – norok2 Jan 21 '20 at 13:10
  • Also note that `yRay` is just a reference to `g.WORLD[yAxis]` and that `id(yRay) == id(g.WORLD[yAxis])` – user2653663 Jan 21 '20 at 13:12

1 Answers1

0

You are likely creating your array as something like

arr = []
bigArr = [arr,arr,arr]

This causes all the arrays to become linked. Use bigArr = [list(arr),list(arr),list(arr)] to create separate objects.

clubby789
  • 2,543
  • 4
  • 16
  • 32