3

I am still a bit confused about how arguments are passed in python. I thought non-primitive types are passed by reference, but why does the following code not print [1] then?

def listTest(L):
    L = L + [1]


def main:
    l = []
    listTest(l)

    print l #prints []

and how could I make it work. I guess I need to pass "a pointer to L" by reference

user695652
  • 4,105
  • 7
  • 40
  • 58

1 Answers1

5

In listTest() you are rebinding L to a new list object; L + [1] creates a new object that you then assign to L. This leaves the original list object that L referenced before untouched.

You need to manipulate the list object referenced by L directly by calling methods on it, such as list.append():

def listTest(L):
    L.append(1)

or you could use list.extend():

def listTest(L):
    L.extend([1])

or you could use in-place assignment, which gives mutable types the opportunity to alter the object in-place:

def listTest(L):
    L += [1]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • I don't like `in-place assignement` because you never know if the object is modified or re-assigned (unless you know exactly what object is passed) – njzk2 Nov 27 '14 at 21:44
  • @njzk2: yes, it is not suitable for mixed-type settings where you expect the original object to always be mutated. – Martijn Pieters Nov 27 '14 at 21:48