[Python-Dev] Re: PEP 322: Reverse Iteration

Mark Russell marktrussell at btopenworld.com
Wed Nov 5 11:48:31 EST 2003

On Wed, 2003-11-05 at 15:56, Alex Martelli wrote:
> def reversed(sequence):
>     for x in xrange(len(sequence)-1, -1, -1): yield sequence[x]
> no __reversed__, no complications, "no nuttin'".

If I was adding this as a library routine, I'd do:

def reversed(sequence):
        seqlen = len(sequence)
    except TypeError:
        sequence = list(sequence)
        seqlen = len(sequence)

    for x in xrange(seqlen-1, -1, -1):
        yield sequence[x]

OK, inefficient for iterators on long sequences, but it works with
enumerate() etc and needs no changes to existing types.


More information about the Python-Dev mailing list