[Python-Dev] List copy and clear (was Re: Inconsistent API for sets.Set and build-in set)
Shane Holloway (IEEE)
shane.holloway at ieee.org
Fri Jul 1 00:04:51 CEST 2005
Raymond Hettinger wrote:
> I would think that that generic clearing is a lark. First, it only
> applies to mutable objects. Second, it would likely only be useful in
> the presence of a generic method for adding to the cleared container (as
> opposed to the existing append(), add(), and setitem() methods for
> lists, sets, and dictionaries respectively). So, for lists, stick with
> the current idiom:
>
> mylist[:] = [] # clear
Pros of list.clear:
+ easy to find in documentation and help()
+ readability & clarity of intention in code
+ commonality with other mutable collections
+ easier to search on "clear()" (well, at least for me...)
Cons of list.clear:
+ Yet another method on list
+ Three ways to do the same thing.
mylist[:] = []
del mylist[:]
mylist.clear()
(Although the implementation will use one of slice operators,
so I guess that depends on how you count ;)
I would agree generic clearing is a lark in terms of programming
feature. However, I have been asked how to clear a list more than a
handful of times. Personally, my opinion is that having a
list.clear method would be a net win, especially since the
implementation can be implemented via __setitem__ or __delitem__.
Are there more Cons than those I have listed?
More information about the Python-Dev
mailing list