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.