[Tutor] Speed of accessing list components

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Sat Jun 26 06:00:13 EDT 2004

On Sat, 26 Jun 2004, Glen Wheeler wrote:

> >>> for i in range(1, len(l)+1):
> ..  print l[-i]

[output cut]

> is this exceptionally slow?  Or the preferred method?

Hi Glen,

It shouldn't be too slow.

But doing a reverse iteration on a list is, admittedly a little awkward in
Python right now.  There's a PEP by Raymond Hettinger that makes reverse
iteration more pleasant:


That PEP proposes to introduce a "reversed()" builtin that will go through
the list sequence in backwards order.  But that's Python 2.4 stuff, which
won't come out officially for a while yet.

In the meantime, though, we can write our own version of reversed():

def reversed(L):
    """Returns an iterator that marches through the elements of L
    in reverse order."""
    n = len(L) - 1
    while n >= 0:
        yield L[n]
        n -= 1

Here's reversed() in action:

>>> for x in reversed(range(10)):
...     print x,
9 8 7 6 5 4 3 2 1 0

Something like reversed() should make the code clearer, as you now don't
have to worry so much about maintaining those list indices by hand.

Hope this helps!

More information about the Tutor mailing list