开发者

How do I stop a Python function from modifying its inputs? [duplicate]

This question already has answers here: How do I clone a list so that it doesn't change unexpectedly after assignment? (23 answers) 开发者_如何学Go Copying nested lists in Python (3 answers) Closed 4 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜