For the following python code
def swap_elements(a):
a[1], a[0] = a[0], a[1]
return a
a = [2, 3]
a = swap_elements(a)
print(a)
, the function swap_elements
will modify a
to itself by a = swap_elements(a)
. From what I understood, it is a shallow copy (ref the accepted answer in In python, is a function return a shallow or deep copy? and a=
here) , which uses the same addresses in the memory. Since the function swap_elements
shallow copies itself to itself, is there any possible issue in locating memory?
E.g., if the shallow copy is doing
a[1] ----> a[2] # in this step a[1] changed
a[2] ----> a[1] # will a[1] at the right-hand side adopts the a[1] in the first step at the left-hand side or the old a[1]?
Is safer to use
b = swap_elements(a)
or
a = copy.deepcopy(swap_elements(a))
?
or
simply swap_elements(a)
, not adding a=
?
I did not find any issue from my experience, but I am not sure if this will lead to problems in general circumstances.