If we make changes to a list passed in as an argument, does it change the list itself?


#1

Question

If we make changes to a list passed in as an argument, does it change the list itself?

Answer

Without going into too much detail, the general answer is yes, changes to a list that is passed in as an argument for a function can change the list itself.

Say for example, that you had the following function that takes in a list, and changes the value at index 1 to the value 20.

def update_list(lst):
  lst[1] = 20

When we run this function with any list as an argument, it will change the value being referenced for that list at index 1.

numbers = [1, 2, 3, 4]
update_list(numbers)
print(numbers) # [1, 20, 3, 4]

names = ["Alice", "Bob", "Carl"]
update_list(names)
print(names) # ["Alice", 20, "Carl"]

The reason for this is that Python lists store references to objects, rather than the objects themselves. So, running this function is changing the reference at index 1 of the lists to be changed to the value 20.


#2

Another way to describe a list is as a pointer object. As described above, each element in the list is a reference to an object in memory somewhere. The objects are not passed into the function but remain where they are. If we manipulate an element, it will simply point to a new object but remain referenced from the same index in the list as before.