0

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?

Vitalii
  • 53
  • 1
  • 7
  • 2
    Python **does not support call by reference semantics**. Ever. For that matter, it doesn't support call by value either. – juanpa.arrivillaga Feb 14 '20 at 23:06
  • 1
    Read https://nedbatchelder.com/text/names.html; assignments to a name have no affect on the previous value of that name. – chepner Feb 14 '20 at 23:07
  • In `ListInitialization` you actually create a new list and assign it to local variable `aList`. If you really wanted to achieve passing-by-reference behavior here, you should replace range like `aList[:] = list(range(10))`. But don't do that! Return a list instead and assign the result to a variable outside of function. – Tupteq Feb 14 '20 at 23:09
  • @Tupteq that would **not** give you call by reference behavior. The distinguishing freature of call by reference here is that *assignments to the parameter are visible in the caller*. So, suppose Python *did* have call by reference. You could do something like `def func(&a): a = 0` then `b = 42; func(b); print(b)` would print 0, but you *cannot do this in Python*. – juanpa.arrivillaga Feb 14 '20 at 23:12
  • @juanpa.arrivillaga Excuse me, but what are the benefits for python users from this approach in passing function parameters? – Vitalii Feb 15 '20 at 09:52
  • @Vitalii I'm not sure what you mean. It's a pretty standard evaluation strategy, used by Java, Python, Ruby, Javascript, Scheme. – juanpa.arrivillaga Feb 15 '20 at 20:37
  • @juanpa.arrivillaga: "For that matter, it doesn't support call by value either." As you said, the passing semantics is identical to Java, and it's called pass-by-value in Java, both here on StackOverflow and elsewhere on the Internet. – newacct Feb 17 '20 at 06:51

0 Answers0