[Tutor] Speed of accessing list components

Glen Wheeler gew75 at hotmail.com
Sat Jun 26 07:35:19 EDT 2004


  Thanks for the reply Danny.  Succinct, informative and well-written -- as
usual ;).
  It turns out that the reverse iteration wasn't too much of a slowdown, but
since I really love generators and other wotnot I'm entering in your
suggestion as soon as I finish this mail.

  Thanks again,
  Glen

>
>
> 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:
>
>     http://www.python.org/peps/pep-0322.html
>
> 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