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

2
  • 1
    Am I the only one why thinks the asker haven't done their homework on this one? It has been asked so many times, why another one? Commented Feb 11, 2014 at 21:00
  • 1
    I think this question has been asked many times, but it is hard to formulate when doing a search query. Commented Feb 11, 2014 at 21:03

4 Answers 4

5

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[:]
Sign up to request clarification or add additional context in comments.

2 Comments

While the OP is using python-3.x, there's a chance that the .clear() method exists (implemented in Python 3.3)
@MaximeLorant that's news for me! fair enough, I updated my answer
2

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

Comments

1

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.