Python's foreach backwards
Asked Answered
K

3

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
Kassiekassity answered 1/11, 2011 at 16:47 Comment(3)
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.Amaze
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.Kassiekassity
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.Abercrombie
N
-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

Nadiya answered 1/11, 2011 at 16:58 Comment(2)
Big +1 for providing a link that explores alternatives.Kassiekassity
-1: It's better to ALSO provide a summary of the linked article, at least. Otherwise if the link goes down, this answer becomes useless.Monarchy
E
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.

Emeryemesis answered 1/11, 2011 at 16:52 Comment(0)
B
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.

Birdsong answered 1/11, 2011 at 16:51 Comment(0)
N
-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

Nadiya answered 1/11, 2011 at 16:58 Comment(2)
Big +1 for providing a link that explores alternatives.Kassiekassity
-1: It's better to ALSO provide a summary of the linked article, at least. Otherwise if the link goes down, this answer becomes useless.Monarchy

© 2022 - 2024 — McMap. All rights reserved.