I have a problem with python here. If I pass an array through a recursive function that adds something to the array each time it is called, the array is modified in each instance
Code:
def test(n,myList):
if n>0:
myList.append("Test")
print ( "BEFORE CALL Instance ", n, myList )
test(n-1,myList)
print ( "AFTER CALL Instance ", n, myList )
else:
return
Execution via test(5,[])
Results:
BEFORE CALL Instance 5 ['Test']
BEFORE CALL Instance 4 ['Test', 'Test']
BEFORE CALL Instance 3 ['Test', 'Test', 'Test']
BEFORE CALL Instance 2 ['Test', 'Test', 'Test', 'Test']
BEFORE CALL Instance 1 ['Test', 'Test', 'Test', 'Test', 'Test']
AFTER CALL Instance 1 ['Test', 'Test', 'Test', 'Test', 'Test']
AFTER CALL Instance 2 ['Test', 'Test', 'Test', 'Test', 'Test']
AFTER CALL Instance 3 ['Test', 'Test', 'Test', 'Test', 'Test']
AFTER CALL Instance 4 ['Test', 'Test', 'Test', 'Test', 'Test']
AFTER CALL Instance 5 ['Test', 'Test', 'Test', 'Test', 'Test']
Actual problem:
Each child function is modifying the array in all parent functions. How can I prevent this?
Copying the list into a new one and modifying it results in the same output as above
myListNew=myList
myListNew.append("Test")