In the code below, 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?