[Tutor] question about removing items from a list

Simon Brunning SBrunning@trisystems.co.uk
Wed, 15 Aug 2001 15:38:21 +0100


> From:	Lance E Sloan [SMTP:lsloan@umich.edu]
> "Allan Crooks" wrote:
> > An even better way would be like this:
> > 
> > del lista[:]
> > 
> > That would delete all items within the list. Doing 'del lista' would 
> > simply delete the list itself.
> 
> What about:
> 
>   lista = []
 
Maybe - it isn't quite the same. Consider the following:

>>> firstlist = [1, 2, 3]
>>> secondlist = firstlist
>>> del firstlist[:]
>>> firstlist
[]
>>> secondlist
[]

versus:

>>> firstlist = [1, 2, 3]
>>> secondlist = firstlist
>>> firstlist = []
>>> firstlist
[]
>>> secondlist
[1, 2, 3]

So, Allan's approach deleted all items from the existing list, whereas yours
creates a new list, and binds the 'firstlist' name to it, but leaves the
existing list intact.

If you have no other references to the original list, then it doesn't make
much difference, but it is worth bearing in mind.
 
> That would give the intended effect, but I wonder what happens to the
> original list that lista pointed to.  Does it hang around in memory,
> or does Python's garbage collection get rid of it as soon as nothing
> points to it any longer?
 
In CPython, it goes away immediately. (This is because it's reference count
drops to zero rather than as a result of GC - CPython GC only picks up
objects caught in cyclic references.)

This is implementation dependant, though - in Jython, Java's GC *will* free
up the memory used by the list. Eventually.

Cheers,
Simon Brunning
TriSystems Ltd.
sbrunning@trisystems.co.uk





-----------------------------------------------------------------------
The information in this email is confidential and may be legally privileged.
It is intended solely for the addressee. Access to this email by anyone else
is unauthorised. If you are not the intended recipient, any disclosure,
copying, distribution, or any action taken or omitted to be taken in
reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot
accept liability for statements made which are clearly the senders own.