In python, is a function return a shallow or deep copy?

◇◆丶佛笑我妖孽 提交于 2019-12-12 10:46:29

问题


In python, if I have

x = y

any modification to x will also modify y, and I can do

x = deepcopy(y)

if I want to avoid modifying y while working on x

Say, instead, that I have:

myFunc():
    return y

def main():
    x = myFunc()

Is it still the case that modifying x will modify y, or since it is a return from another function it will be like a deepcopy?


回答1:


It will be a shallow copy, as nothing has been explicitly copied.

def foo(list):
    list[1] = 5
    return list

For example:

>>> listOne = [1, 2]
>>> listTwo = [3, 4]
>>> listTwo = listOne
>>> foo(listTwo)
[1, 5]
>>> listOne
[1, 5]



回答2:


In python everything is a reference. Nothing gets copied unless you explicitly copy it.

In your example, x and y reference the same object.



来源:https://stackoverflow.com/questions/42032384/in-python-is-a-function-return-a-shallow-or-deep-copy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!