In the following code, the function modify_list want to modify b, but it failed, the print result is [1,2,3]. why hasn't the list a changed?
def modify_list(b):
b = [1,2]
a = [1,2,3]
modify_list(a)
print(a)
In the following code, the function modify_list want to modify b, but it failed, the print result is [1,2,3]. why hasn't the list a changed?
def modify_list(b):
b = [1,2]
a = [1,2,3]
modify_list(a)
print(a)
you are declaring other local variable b, if you want to mutate you can do:
b[:] = [1, 2]
or even better you can return your desired value for list a
if you want to change your list a
value you can assign the desired value:
a = [1, 2]
If you want something like this to work you can do:
def modify_list(b):
return [1,2]
a = [1,2,3]
a = modify_list(a)
print(a)
Or
def modify_list(b):
b[:] = [1,2]
a = [1,2,3]
modify_list(a)
print(a)