Question about idioms for clearing a list

Bryan Olson fakeaddress at nowhere.org
Wed Feb 8 16:14:33 EST 2006


Magnus Lycka wrote:
> Ed Singleton wrote:
> 
>> The point is that having to use del to clear a list appears to the
>> inexperienced as being an odd shaped brick when they've already used
>> the .clear() brick in other places.
> 
> 
> Agreed. The smart way to go from this stage of surprise is
> not to assume that Python is broken, but to try to understand
> how lists are different from e.g. dicts, and why the so-much-
> smarter-than-me Python designers made it like this.

That two of Python's three built-in mutable collections support
clear() is clearly a historical artifact.

> Not that Python is perfect, but when you don't get a
> "sorry, this change would break existing code, won't happen
> until Python 3.0"-resonse, but a "study this more"-response,
> the smart thing is to open your mind and try to fully grok
> this.

The original question was about idioms and understanding, but
there's more to the case for list.clear. Python is "duck typed".
Consistency is the key to polymorphism: type X will work as an
actual parameter if and only if X has the required methods and
they do the expected things.

Emptying out a collection is logically the same thing whether
that collection is a list, set, dictionary, or user-defined
SortedBag. When different types can support the same operation,
they should also support the same interface. That's what
enables polymorphism.


-- 
--Bryan



More information about the Python-list mailing list