Search code examples
pythonpass-by-referencepass-by-value

why del keyword does not delete a list when passed to a function


in the following code when i use del keyword to delete the formal parameter a, and then print it outside the function the list that is passed still exists.

lst = [1,2,3]
def func(a):
    print lst
    lst.append(4) #this is modified as it is by default passed by reference
    print lst
    print locals
    del a # this does not delete the lst! why?
    print locals
func(a)
print lst #still exists! 

Solution

  • It's a problem of an object and the names you use to reference said object, your problem is very similar (except that in your problem the names live in different namespaces) to the following one:

    a = [1, 2]
    b = a
    b.append(3)
    del b
    

    do you think that you deleted the list object? No. Another analogy for another domain, the shell

    $ echo 1 > a
    $ ln a b
    $ echo 2 >> b
    $ rm b
    $ cat a