Question about idioms for clearing a list

Raymond Hettinger python at rcn.com
Fri Feb 10 05:43:13 EST 2006


> > If you're asking why list's don't have a clear() method, the answer is
> > that they already had two ways to do it (slice assignment and slice
> > deletion) and Guido must have valued API compactness over collection
> > polymorphism.  The latter is also evidenced by set.add() vs
> > list.append() and by the two pop() methods having a different
> > signatures.
[bonono]
> Sounds to me that it is a preference(style, whatever), rather than some
> other posts of this thread argued that "del L[:]" is better.

It was simply design decision reflecting Guido's values on language
economics.


> > If you're asking why your specific case looked so painful, I suspect
> > that it only looked hard because the adaptation was force-fit into a
> > lambda (the del-statement or slice assignment won't work as an
> > expression).  You would have had similar difficulties embedding
> > try/except logic or a print-statement.  Guido, would of course
> > recommend using a plain def-statement:
> >
> >     L = list()
> >     def L_clearer(L=L):
> >         del L[:]
> >     for listbunch in buncher(src, '', L, L.append, L_clearer):
> >         print listbunch
> >
> Is that really "clearer" ? While it is still very localized(just read a
> few lines up for the definition), buncher(src, '', L.append, L.clear)
> seems to be clearer to me, especially there are two similar construct
> on set/dict above,

Hmm, my post was so long that the main points were lost:

* the example was tricky only because of the unnecessary in-place
update requirement

* eliminating that requirement solves the adaptation problem and
simplifies the client code

* the constructor API is polymorphic, use it

* adding clear() doesn't help with the other API variations between
set, list, dict, etc.

* Guido's decision for distinct APIs is intentional (i.e. set.add vs
list.append)

* Alex's adapter PEP is likely a better solution for forcing
polymorphism on unlike APIs

* When a lambda becomes awkward, Guido recommends a separate def

* Guido has no sympathy for atrocities resulting from squeezing
everything into one line

* Alex's example can be simplified considerably:

    def buncher(sourceit, sentinel, constructor):
        for k, g in groupby(sourceit, lambda x: x != sentinel):
            if k:
                yield constructor(g)

    for setbunch in buncher(src, '', set):
        print setbunch

* The improved version has no need for list.clear().   End of story.


Raymond




More information about the Python-list mailing list