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])
You are off on how Python works:
Python fundamental concept is the use of names and values. When you write down a name in code it stands for the value attached to it during runtime. In this case
list_[4]is a name that stands for the value7.When you want to change something you must use one of it’s names. Here you want to change the
list_, so you have to do this: