I meet this problem when implementing my own swap()
method with Python
def swap(a,b):
temp=a
a=b
b=temp
list_=[5,4,6,3,7]
swap(list_[4],list_[2])
I expexted list_ to be updated with swap()
call, since list_[4]
and list_[2]
are to be assigned new values during function call. However, list_
remains unchanged:
list_
[5, 4, 6, 3, 7]
I misunderstand why swap function call is dealing with a copy. I don't want to add a list argument to my swap function nor return the list during swap() call since I want the method to be adaptable to other datastructures, like in
swap(mat[0][1],mat[2,3])