Question about idioms for clearing a list

Steven D'Aprano steve at REMOVETHIScyber.com.au
Mon Feb 6 09:01:43 EST 2006


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

Perhaps it is arguable that there is no need for a clear method because
L[:] = [] is so easy to do. Personally, while I agree that it is easy, it
is hardly intuitive or obvious, and I too would prefer an explicit clear
method for mutable sequences.


-- 
Steven.




More information about the Python-list mailing list