0

I'm getting this issue where a change I make within a for-loop seemingly affects all things outside of its for-loop. I looked into global vs. local variables, but I don't think that's the issue here.

Given a list of boards (which themselves are matrixes or list of lists)...

boards_list = [
    [
        [12, 79, 33, 36, 97, 0],
        [82, 38, 77, 61, 84, 0],
        [55, 74, 21, 65, 39, 0],
        [54, 56, 95, 50, 2, 0],
        [45, 68, 31, 94, 14, 0],
        [0, 0, 0, 0, 0, 0]
    ],
    [
        [95, 26, 80, 25, 62, 0],
        [79, 91, 70, 76, 61, 0],
        [98, 97, 17, 75, 23, 0],
        [71, 30, 21, 52, 29, 0],
        [20, 54, 32, 12, 31, 0],
        [0, 0, 0, 0, 0, 0]
    ],
    [
        [35, 31, 86, 36, 52, 0],
        [18, 50, 79, 60, 67, 0],
        [98, 3, 51, 46, 25, 0],
        [4, 61, 55, 87, 70, 0],
        [94, 39, 68, 27, 14, 0],
        [0, 0, 0, 0, 0, 0]
    ]
]

Let's say I want to change the 3rd value in the last row of the 2nd board to an 'X' (aka... boards_list[1][-1][2] = 'X'), but I insist on using a for-loop to do that. Here is my sample code:

for index, board in enumerate(boards_list):
    if index == 1:
        board[-1][2] = 'X'

In my head, I think the above code should do exactly boards_list[1][-1][2] = 'X'. However, when I check the last row of every board afterwards, I end up with this!!

for board in boards_list:
    print(board[-1])

OUTPUT:
[0, 0, 'X', 0, 0, 0]
[0, 0, 'X', 0, 0, 0]
[0, 0, 'X', 0, 0, 0]

Why did EVERY last row of all boards change? Shouldn't it have only been my 2nd board (aka boards_list[1])?

NOTE: I understand that there are more direct ways of changing my specified value to 'X', but my aim here is to fix what I'm not understanding about for-loops.

Thanks.

  • 1
    Um, is that list generated by a list comprehension or something? Because defining it explicitly like you've done here [doesn't](https://ideone.com/kKDv8T) produce your output – dumbPotato21 Dec 25 '21 at 18:34
  • 2
    Show us the actual initialization of `boards_list` - it's obviously not the code you showed at the top of your question. I suspect you've done something like `[[[0]*6]*6]*3` that doesn't create individual lists at each level, just multiple references to the same inner list. – jasonharper Dec 25 '21 at 18:34
  • 1
    Or if it really is initialized like that, then you created an aliasing problem at some point after the initialization. – user2357112 Dec 25 '21 at 18:34
  • 1
    Copied all your code and got correct result – kosciej16 Dec 25 '21 at 18:35
  • Given your issue, this is what is linked in the duplicate. Ensure that when you create the board you have different lists, and not multiple times the same object. – mozway Dec 25 '21 at 18:39

0 Answers0