Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending a list inside a function

Tags:

python

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

like image 391
user695652 Avatar asked Oct 15 '25 08:10

user695652


1 Answers

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]
like image 84
Martijn Pieters Avatar answered Oct 16 '25 22:10

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!