user695652
user695652

Reputation: 4275

Appending a list inside a function

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

Upvotes: 4

Views: 7606

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121446

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]

Upvotes: 6

Related Questions