Question about idioms for clearing a list

Steve Holden steve at holdenweb.com
Mon Feb 6 08:35:10 EST 2006


Will McGugan wrote:
> Steven Watanabe wrote:
> 
>>I know that the standard idioms for clearing a list are:
>>
>>  (1) mylist[:] = []
>>  (2) del mylist[:]
>>
>>I guess I'm not in the "slicing frame of mind", as someone put it, but
>>can someone explain what the difference is between these and:
>>
>>  (3) mylist = []
>>
>>Why are (1) and (2) preferred? I think the first two are changing the
>>list in-place, but why is that better? Isn't the end result the same?
> 
> 
> 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!

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC                     www.holdenweb.com
PyCon TX 2006                  www.python.org/pycon/




More information about the Python-list mailing list