How do I stop a Python function from modifying its inputs? [duplicate]
I've asked almost this just before now, but the fix doesn't work for x = [[]], which I'm guessing is because it is a nested list, which is what I will be working with.
def myfunc(w):
y = w[:]
y[0].append('What do I need to do to get this to work here?')
y[0].append('When I search for the manual, I get pointed to python.org, but I can\'t find the answer there.')
return y
x = [[]]
z = myfunc(x)
print(x)
Here's how you could fix your problem:
def myfunc(w):
y = [el[:] for el in w]
y[0].append('What do I need to do to get this to work here?')
y[0].append('When I search for the manual, I get pointed to python.org, but I can\'t find the answer there.')
return y
x = [[]]
z = myfunc(x)
print(x)
The thing about [:] is that it's a shallow copy. You could also import deepcopy from the copy module to achieve the correct result.
Use the copy module and to create deep copies of the inputs with the deepcopy function. Modify the copies and not the original inputs.
import copy
def myfunc(w):
y = copy.deepcopy(w)
y[0].append('What do I need to do to get this to work here?')
y[0].append('When I search for the manual, I get pointed to python.org, but I can\'t find the answer there.')
return y
x = [[]]
z = myfunc(x)
print(x)
Before you use this method, read up about the problems with deepcopy (check the links above) and make sure it's safe.
精彩评论