brolija brolija - 1 month ago 10
Python Question

Input parameter change as loop calls for another def (python 3.0), why?

I can just not figure out why my input parameter(board) is changing in the loop..

The def iterate takes in the list "board" from def initiate. And it should do this once, and I checked, it is only calling def initiate once. The problem occurs in the loop "for i in range(0,size()):" in def iterate. Here, the list "old_board" somehow changes. If I have 5 rounds and 5 lists in the list "old_board", the second round changes the values of old_board[1] and so on.. Why is this happening? And how can I solve it?

(Parameter list and list in the loop should be equal)

This is the output:

"This is the parameter list : [[1, 1, 0, 1, 0], [1, 1, 1, 0, 1], [0, 0, 1, 1, 1], [1, 1, 0, 1, 1], [1, 0, 0, 1, 0]]

This is the list in the loop: [[1, 1, 0, 1, 0], [1, 1, 1, 0, 1], [0, 0, 1, 1, 1], [1, 1, 0, 1, 1], [1, 0, 0, 1, 0]]

This is the list in the loop: [[0, 0, 0, 1, 0], [1, 1, 1, 0, 1], [0, 0, 1, 1, 1], [1, 1, 0, 1, 1], [1, 0, 0, 1, 0]]

This is the list in the loop: [[0, 0, 0, 1, 0], [1, 1, 0, 0, 0], [0, 0, 1, 1, 1], [1, 1, 0, 1, 1], [1, 0, 0, 1, 0]]

This is the list in the loop: [[0, 0, 0, 1, 0], [1, 1, 0, 0, 0], [0, 0, 0, 1, 0], [1, 1, 0, 1, 1], [1, 0, 0, 1, 0]]

This is the list in the loop: [[0, 0, 0, 1, 0], [1, 1, 0, 0, 0], [0, 0, 0, 1, 0], [1, 1, 0, 1, 0], [1, 0, 0, 1, 0]]"

This is the code:

def iterate(board):
old_board = board
print('This is the parameter list :',old_board)
new_board = board
living = 0 # Value of alive cells in the future new board

for i in range(0,size()): # Nestled loop that iterate through the old board
print('This is the list in the loop:',old_board)
for j in range(0,size()): # and sets new values depending on the status of each old cell
new_value = living_neighbors(i,j,old_board)[1]
new_board[i][j] = new_value
living += new_value
print(new_board)
print(living)

return (living, new_board)
iterate(initiate()[0])

Answer

By doing this

old_board = board
new_board = board 

You don't create new objects but merely new references to the existing ones. You can use the copy module or the syntax suggested by Alex to create new objects.

from copy import deepcopy
old_board = deepcopy(board)

Here you can find a detailed explanation: http://www.python-course.eu/deep_copy.php

Comments