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]
>>>
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With