Question about idioms for clearing a list
Steven D'Aprano
steve at REMOVETHIScyber.com.au
Mon Feb 6 16:56:00 EST 2006
On Mon, 06 Feb 2006 09:39:32 -0500, Dan Sommers wrote:
> 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?
What relevance is this? If there is one and only one reference to the list
L, then it will be garbage collected when L is rebound. I never denied
that. I pointed out that, in the general case, you may have multiple
references to the list (not all of which are bound to names), and
rebinding the name L will NOT have the side-effect of clearing the list.
> 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.
Precisely, just as my example shows.
--
Steven.
More information about the Python-list
mailing list