2
    def swap(array, i):
        array[i], array[(i+1)%len(array)] = array[(i+1)%len(array)], array[i]
        return array 

Why my swap functions swap in place? I mean in the swap function 'array' is local variable and i am swapping the elements of the local variable and returning the 'array' then why changes is made in the list i pass. for example if there i a list a = [1,2,3,4] after calling swap(a,0) it should return [2,1,3,4] which it does but it also modifying the list 'a' i passed?

Mohit Solanki
  • 2,122
  • 12
  • 20
  • 1
    Because lists are mutable. You are passing `array` as a list and performing a swap, which modifies it in-place – Wondercricket Jun 30 '17 at 15:36
  • Possible duplicate of [How do I pass a variable by reference?](https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference) (see the accepted answer for a complete explanation of your issue) – jadsq Jun 30 '17 at 15:39
  • Lists are pointers to a memory location. You need to perform a copy operation or it will act on the same chunk of memory no matter what function space it is in. list_copy = original_list[:] – Sebastian Jun 30 '17 at 15:40

1 Answers1

1

Python, like many object oriented languages, passes function arguments by sharing, rather than by copying.

You should think of array as a label to a specific bit of memory. If your function def f(a) takes a variable called a, whenever you call swap(some_variable), the memory which stores some_variable becomes available inside your function with the label a.

This is why the variable is changed in your example. If you want to leave the original value of array unchanged, you need to first copy it, like in the code below.

def swap(original_array, i):
    # use list() return a copy of the list
    new_array = list(original_array)
    # do work on the copy of the list, which is a local var
    new_array[i], new_array[(i+1)%len(new_array)] = new_array[(i+1)%len(new_array)], new_array[i]
    # return the value of the local var
    return new_array 

# setup a list
a = [1,2,3,4]
# function still works
assert swap(a, 2) == [1,2,4,3]
# but it does not change the value passed to it
assert a = [1,2,3,4]
# and its local variable new_array is not available in this scope
assert 'new_array' not in dir()
Dom Weldon
  • 1,728
  • 1
  • 12
  • 24