Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Pass by reference and slice assignment

In Python, lists are passed by reference to functions, right?

If that is so, what's happening here?

>>> def f(a):
...     print(a)
...     a = a[:2]
...     print(a)
...
>>> b = [1,2,3]
>>> f(b)
[1, 2, 3]
[1, 2]
>>> print(b)
[1, 2, 3]
>>>
like image 900
Diego Puertas Avatar asked Dec 05 '22 14:12

Diego Puertas


2 Answers

In the statement:

a = a[:2]

you are creating a new local (to f()) variable which you call using the same name as the input argument a.

That is, what you are doing is equivalent to:

def f(a):
    print(a)
    b = a[:2]
    print(b)

Instead, you should be changing a in place such as:

def f(a):
    print(a)
    a[:] = a[:2]
    print(a)
like image 175
AGN Gazer Avatar answered Dec 14 '22 02:12

AGN Gazer


When you do:

a = a[:2]

it reassigns a to a new value (The first two items of the list).

All Python arguments are passed by reference. You need to change the object that it is refered to, instead of making a refer to a new object.

a[2:] = []
# or
del a[2:]
# or
a[:] = a[:2]

Where the first and last assign to slices of the list, changing the list in-place (affecting its value), and the middle one also changes the value of the list, by deleting the rest of the elements.

like image 41
Artyer Avatar answered Dec 14 '22 04:12

Artyer