>>> 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 []?
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[:]
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[:]
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