Python - why doesn't the list change?

>>> c=[1,100,3]
>>>def nullity (lst):
   lst=[]
>>>nullity (c)
>>>c
[1,100,3]

Why does c not return []? Doesn't that nullity(c)mean c=lstthat both of you are now pointing to []?

+4
source share
4 answers

Python has pass-by-value semantics, which means that when you pass a parameter to a function, it gets a copy of the object reference, but not the object itself. So, if you reassign a function parameter to something else (like you), the destination is local to the function, the original object "outside" the function remains unchanged. A completely different situation arises if you change something inside the object:

def test(a):
    a[0] = 0

lst = [1, 2, 3]
test(lst)
lst
=> [0, 2, 3]

, lst a . - , Python 3.2 clear() ( Python 3.3), here . , Python 2.x 3.x:

def nullity(lst):
    del lst[:]
+5

lst list. , :

del lst[:]
+2

Python . , "lst" , .

, :

def nullity (lst):
    lst.clear()  # With Python >= 3.3
+1

id()

In [14]: c=[1,2,3]

In [15]: def nullity (lst):
    ...:     print id(lst)
    ...:     lst=[]
    ...:     print id(lst)
    ...:     

In [16]: id(c)
Out[16]: 33590520

In [17]: nullity(c)
33590520
33591024

, , .

+1
source

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


All Articles