Home > Net >  My function is changing an input variable how can I prevent or fix this?
My function is changing an input variable how can I prevent or fix this?

Time:12-02

The for loop makes a list with 10 sub-lists with 10 values each. The WD() function is supposed to change values in the sub-lists and return the new list. The problem is that even with the return commented out, it changes the input variable DD. Why is it doing this and how can I prevent this from happening?

DD = []
for i in range(10):
   DD  = [["  ","  ","  ","  ","  ","  ","  ","  ","  ","  "]]

def WD(x, y, D, V): # x=sub list index  y=list index D=list V=replace with
    n = D[y-1]
    n[x-1] = V
    D[y-1] = n
    # return D

WD(5, 5, DD, "##")
print(DD)

Here is the output

[['  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  '], ['  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  '], ['  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  '], ['  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  '], ['  ', '  ', '  ', '  ', '##', '  ', '  ', '  ', '  ', '  '], ['  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  '], ['  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  '], ['  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  '], ['  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  '], ['  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ']]

CodePudding user response:

list objects are mutable in Python, It means if you pass them to functions and edit that argument, the main list will be changed. For preventing this problem you can create a copy from the input list and pass that to the function

import copy

DD = []
for i in range(10):
   DD  = [["  ","  ","  ","  ","  ","  ","  ","  ","  ","  "]]

def WD(x, y, D, V): # x=sub list index  y=list index D=list V=replace with
    n = D[y-1]
    n[x-1] = V
    D[y-1] = n
    # return D

new_list = copy.deepcopy(DD)
WD(5, 5, new_list, "##")
print(DD)
  • Related