About some problems due to passing function's parameters by reference

Hi there!
In the below code, I’m trying to change Python list inside functions through passing it by reference.

def ListInitialization(aList):
aList = list(range(10))
print("“ListInitialization” aList print: ", aList, “\n”)

def ListEdit(aList):
aList[2] = 2222
print("“ListEdit” aList print: ", aList, “\n”)

if name == “main”:
aList =
ListInitialization(aList)
print("“Main” after “ListInitialization” aList print: “, aList, “\n”)
aList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
ListEdit(aList)
print(”“Main” after “ListEdit” aList print: ", aList, “\n”)

The output of the above code is:

“ListInitialization” aList print: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
“Main” after “ListInitialization” aList print:
“ListEdit” aList print: [0, 1, 2222, 3, 4, 5, 6, 7, 8, 9]
“Main” after “ListEdit” aList print: [0, 1, 2222, 3, 4, 5, 6, 7, 8, 9]

Why didn’t the ListInitialization function changes to aList go beyond the ListInitialization function? But the ListEdit function changes made to aList remained after the ListEdit was completed?

Many thanks!

Your ListInitiallization function assigns to the name aList, so it is a local name. It does not re-assign the variable you called the function with.

In ListEdit, you don’t assign to the name aList. Assigning to aList[2] is equivalent to calling a method on in: aList.__setitem__(2, 2222). So it’s mutating the object that was passed in.

My talk Python Names and Values has much more detail about this.