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 =
print("“Main” after “ListInitialization” aList print: “, aList, “\n”)
aList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
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!

1 Like

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.

1 Like

Thank you very much for your detailed explanation, sir. May I ask about your article “Names and Values ​​of Python”? Python is a living organism that is constantly evolving and changing. Did these changes affect the relevance of your article for the last years?

1 Like

Many things have changed in Python since I wrote that talk, but the things I describe in that talk have stayed the same.

1 Like