Newbi Q: Recursively reverse lists but NOT strings?
Bruno Desthuilliers
bdesth.quelquechose at free.quelquepart.fr
Tue Oct 16 18:29:41 EDT 2007
Steven D'Aprano a écrit :
(snip)
> def myreversed(sequence):
> if isinstance(sequence, basestring):
> return type(sequence)().join(reversed(sequence))
> else:
> return type(sequence)(reversed(sequence))
>
> (in fact, that's so simple I wonder why the built-in reversed() doesn't
> do that).
Because it returns an iterator, not a sequence. Building back the
appropriate sequence type from when needed it is usually a definitive
no-brainer, and there are case where you definitively *don't* want a
full sequence to be built (like when iterating backward over a
millions-element long list...).
Definitively the right design choice here IMHO.
My 2 cents
More information about the Python-list
mailing list