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

2

11

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?

Tyrannize answered 3/2, 2017 at 20:18 Comment(2)
Can you be more specific. In your case it's not clear where does 'y' come from. The code you posted will not run because 'y' is not knownOctoroon
Functions don't return any sort of copies. In other words, it is neither.Cinquain
S
8

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]
Seafowl answered 3/2, 2017 at 20:28 Comment(0)
W
21

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

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

Wabble answered 3/2, 2017 at 20:22 Comment(3)
I think this is a really important principle to learn in Python: assignment never makes a copy. You can extend that to function returns as well.Favin
I knew that about assignment in a function, I was not sure about return because I think it is different in JavaTyrannize
Why does extending a list of ravel()ed ndarrays does not create a shallow copy of the original ndarrays?Fernando
S
8

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]
Seafowl answered 3/2, 2017 at 20:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.