11

Does python have a means of doing foreach backwards? I'm hoping to do a filter() (or list comprehension) and reverse a list at the same time, so that I can avoid doing it separately (which I suspect will be slower). I'm using python 2.4 (I have to unfortunately), but I'm also curious what the list comprehension solution would be in python 3.0.

Edit Both of these solutions appear to be the same:

python -m timeit -s 'x=[1,2,3,4,5]*99; filter(lambda x: x == 5, reversed(x))' 
100000000 loops, best of 3: 0.0117 usec per loop
python -m timeit -s 'x=[1,2,3,4,5]*99; x.reverse(); filter(lambda x: x == 5, x)'    
100000000 loops, best of 3: 0.0117 usec per loop
shadowland
  • 757
  • 1
  • 6
  • 20
  • 2
    I'm not sure why you would suspect it would be slower, at least to a point that you should worry about it. This sounds a bit like premature optimization to me. – Wayne Werner Nov 01 '11 at 16:52
  • It just seemed to me like filter() goes through once and reverse() goes through a 2nd time, so I figured there would be a way to do this with one traversal. – shadowland Nov 01 '11 at 17:05
  • 3
    You could always unroll the two manually, but that won't be faster if written in Python, and the overhead almost certainly (*especially* if you don't have hard data to prove otherwise) isn't worth writing a C extension module. And that's assuming that you write the comparision in C as well, calling back into Python for each item will greatly reduce any potential gain. –  Nov 01 '11 at 17:29

3 Answers3

32

You are looking for the built-in reversed():

>>> for i in reversed(range(5)):
...     print i
... 
4
3
2
1
0

This iterates over the sequence in reverse, without creating an additional copy of your list.

Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
2

It is not the right way to do it in the same time with filtering. Just use reverse, it will be much more optimized than doing it manually.

Lachezar
  • 6,523
  • 3
  • 33
  • 34
-1

Here is a good compilation of things you could do to achieve backward iteration: http://christophe-simonis-at-tiny.blogspot.com/2008/08/python-reverse-enumerate.html

GeneralBecos
  • 2,476
  • 2
  • 22
  • 32