Why is del(ete) a statement instead of a method?

Chad Netzer cnetzer at mail.arc.nasa.gov
Tue Oct 8 22:01:48 EDT 2002


On Tuesday 08 October 2002 18:44, Greg Brunet wrote:
> I'm just trying to learn Python, and one thing that struck me as odd
> was that to delete a specific list element, I need to use a statement
> instead of a method like I use for almost everything else I do on the
> list.  This seems a bit inconsistent.  Why wouldn't it be a method?

Because del works on a lot more than just lists; you can 'del' any object 
(although it doesn't mean the object actually is deleted from use; typically 
it just means the local reference to it is removed)

And you can remove objects from a list using methods; the .remove() method 
does just that.  'del' is often more handy, though, since you can refer to 
the list member to delete by position (or index, technically), rather than 
knowing the id of the object to remove:

a = [10, 11, 12]

del a[ 1 ]   # remove 11 from the list

or

a.remove( a[ 1 ] )   # Also removes 11 from the list

However, to delete the whole list from the local scope:

del a

which is NOT the same as:

a. remove( a[ 0 ] )
a.remove( a[ 1 ] )
a.remove( a[ 2 ] )

which make an empty list, but 'a' still exists in the scope.

But, even after 'del a', although you won't be able to refer to the list 'a', 
by that name, in the local scope, it may still exist if another reference to 
it exists:

a = [ 10, 11, 12]
b = a
del a

The list is still there, and can be referred to as 'b', but not 'a'.

-- 

Chad Netzer
cnetzer at mail.arc.nasa.gov




More information about the Python-list mailing list