Question about idioms for clearing a list

Dan Sommers me at privacy.net
Mon Feb 6 09:39:32 EST 2006


On Tue, 07 Feb 2006 01:01:43 +1100,
Steven D'Aprano <steve at REMOVETHIScyber.com.au> wrote:

> On Mon, 06 Feb 2006 13:35:10 +0000, Steve Holden wrote:
>>> I'm wondering why there is no 'clear' for lists. It feels like a common
>>> operation for mutable containers. :-/
>>> 
>> Because it's just as easy to create and assign a new empty list (and 
>> have the old unused one garbage collected).
>> 
>> l = []
>> 
>> is all you need!

> Not so. If that logic were correct, then dicts wouldn't need a clear
> method either, because you could just assign a new empty dict with d = {}.

> But your own sentence tells us why this is not sufficient: because you
> aren't emptying the list, you are reassigning (rebinding) the name. The
> old list still exists, and there is no guarantee that it will be garbage
> collected, because there is no guarantee that it isn't in use somewhere
> else:

> L = [0,1,2]
> D = {"key": L}
> L = []  # rebinds the name L, but the list instance still exists

That is a red herring.  Consider this:

L = [object(), object()]
O = L[1]
L = [] # or insert your favorite list-clearing/emptying statement here

What damage is done now that O is still referring to one of the items
that used to be in L?

The trouble begins when references to "the list to which L refers" end
up somewhere else.  Then we have to wonder if rebinding L will leave
some other block of code with an outdated list.

Regards,
Dan

-- 
Dan Sommers
<http://www.tombstonezero.net/dan/>



More information about the Python-list mailing list