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()