Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python- why the list doesn't modified?

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

Why c doesn't return []? Isn't nullity(c) mean c=lst so thy both point now at []?

like image 416
user7777777 Avatar asked Jan 11 '23 05:01

user7777777


2 Answers

Python has pass-by-value semantics, meaning that when you pass a parameter to a function, it receives a copy to the object's reference, but not the object itself. So, if you reassign a function parameter to something else (as you did), the assignment is local to the function, the original object "outside" the function remains unchanged. A completely different situation happens if you change something inside the object:

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

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

In the above snippet the list's elements were changed, that's because both lst and a are pointing to the exact same object. Now back to the original question - notice that in Python 3.2 and below there isn't a clear() method (it was added in Python 3.3), here is a related discussion. But you can do this for the same effect, and it'll work in Python 2.x and 3.x:

def nullity(lst):
    del lst[:]
like image 148
Óscar López Avatar answered Jan 13 '23 20:01

Óscar López


You're reassigning local variable lst to a new empty list. To empty an existing list, you need to delete all its members:

del lst[:]
like image 34
mhlester Avatar answered Jan 13 '23 19:01

mhlester