Question about idioms for clearing a list

bonono at gmail.com bonono at gmail.com
Fri Feb 10 04:17:18 EST 2006


Raymond Hettinger wrote:
> [Alex]
> > So what is the rationale for having list SO much harder to use in such a
> > way, than either set or collections.deque?
>
> Sounds like a loaded question ;-)
>
> 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.
Sounds to me that it is a preference(style, whatever), rather than some
other posts of this thread argued that "del L[:]" is better.

>
> 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, even the Alex's lambda form conveys more info, IMO.
Usng the new partial function, may be it can be written as :

buncher(src.'', L, L.append, partial(L.__delslice__, 0, sys.maxint))

#assuming list can have at at most maxint items.




More information about the Python-list mailing list