user7777777
user7777777

Reputation: 217

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

Upvotes: 4

Views: 104

Answers (4)

Óscar López
Óscar López

Reputation: 236004

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

Upvotes: 5

mtanti
mtanti

Reputation: 834

Python does not allow you to replace parameters. You are only changing what "lst" refers to within the function, but it does not affect the calling code.

Instead change the list itself by clearing it:

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

Upvotes: 1

Fredrik Pihl
Fredrik Pihl

Reputation: 45652

Lets use the id() function

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

When doing the reassignment a new local object is created which is not the same as the one used when calling the function.

Upvotes: 1

mhlester
mhlester

Reputation: 23221

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

Upvotes: 2

Related Questions