Python: passing by reference and slice destination

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

If so, what happens 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]
>>>
+4
source share
3 answers

Indeed, objects are passed by reference, but a = a[:2]basically creates a new local variable that points to a list fragment.

To modify a list object, you can assign it to its slice (slice assignment).

Consider aand bis equivalent to your global band local a, is the assignment of aa new object has no effect on b:

>>> a = b = [1, 2, 3]    
>>> a = a[:2]  # The identifier `a` now points to a new object, nothing changes for `b`.
>>> a, b
([1, 2], [1, 2, 3])
>>> id(a), id(b)
(4370921480, 4369473992)  # `a` now points to a different object

The slice assignment works as expected:

>>> a = b = [1, 2, 3]    
>>> a[:] = a[:2]  # Updates the object in-place, hence affects all references.
>>> a, b
([1, 2], [1, 2])
>>> id(a), id(b)
(4370940488, 4370940488)  # Both still point to the same object

: slice, ?

+3

:

a = a[:2]

(to f()), , a.

, , :

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

a , :

def f(a):
    print(a)
    a[:] = a[:2]
    print(a)
+5

:

a = a[:2]

a ( ).

Python . , , , a .

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

, ( ), , .

+5
source

Source: https://habr.com/ru/post/1682343/


All Articles