Python foreach back

Does python have the ability to do foreach in the opposite direction? I hope to make a filter () (or list comprehension) and expand the list at the same time, so that I can avoid it separately (which, I suspect, will be slower). I am using python 2.4 (I should, unfortunately), but I am also interested that the solution for list comprehension will be in python 3.0.

Edit Both of these solutions look 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 
+6
source share
3 answers

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

+1
source

You are looking for built-in reversed() :

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

This is repeated in sequence in reverse order without creating an additional copy of your list.

+15
source

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

+1
source

Source: https://habr.com/ru/post/900539/


All Articles