1

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.

Geositta
  • 81
  • 7
  • No where in your code do you make a copy of the list – Iain Shelvington Feb 13 '22 at 16:27
  • The accepted answer in https://stackoverflow.com/questions/42032384/in-python-is-a-function-return-a-shallow-or-deep-copy said as a shallow copy? – Geositta Feb 13 '22 at 16:32
  • 1
    The answer with the most votes on the question is correct https://stackoverflow.com/a/42032437/548562. You are just passing around a reference to a single list object – Iain Shelvington Feb 13 '22 at 16:35
  • So in the accepted answer in https://stackoverflow.com/questions/42032384/in-python-is-a-function-return-a-shallow-or-deep-copy/42032437#42032437, why `listOne` changed its value? is that due to it is modified in `list[1] = 5` and within the scope of variable, but not really about shallow copy issue, is that correct? And in my code `a = swap_elements(a)`, is `=` a shallow copy (perhaps i should not add `a=`)? – Geositta Feb 13 '22 at 16:41
  • 1
    In the answer, the line `listTwo = listOne` makes `listTwo` reference the same object as `listOne` so when the `foo` function is run it updates the __one__ list that both variables reference. The `=` operator doesn't copy anything, it just makes the name/variable on the left side reference/point-to the object on the right, `a = b` just makes the variable/name `a` now reference the same object that `b` references, no copying involved – Iain Shelvington Feb 13 '22 at 16:45
  • Mandatory link to [Ned Batchelder](https://nedbatchelder.com/text/names.html) – quamrana Feb 13 '22 at 16:46
  • @quamrana thanks. I am reading the link. – Geositta Feb 13 '22 at 16:50

0 Answers0