Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's foreach backwards

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
like image 800
shadowland Avatar asked Nov 01 '11 16:11

shadowland


People also ask

Can you iterate backwards in Python?

But Python does have a built-in reversed function. If you wrap range() inside reversed() , then you can print the integers in reverse order. range() makes it possible to iterate over a decrementing sequence of numbers, whereas reversed() is generally used to loop over a sequence in reverse order.

How do you do a forEach backwards?

To use the forEach() method on an array in reverse order:Use the slice() method to get a copy of the array. Use the reverse() method to reverse the copied array. Call the forEach() method on the reversed array.

How do I iterate a string backwards in Python?

Use the reversed() function to iterate over a string in reverse order, e.g. for char in reversed(my_str): . The reversed() function takes an iterator, such as a string, reverses it and returns the result. Copied!

How do you read a list backwards in Python?

To reverse a Python list in place, use the reverse() method. If you only need to create a reversed iterator, use the reversed() function.


2 Answers

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.

like image 78
Andrew Clark Avatar answered Sep 21 '22 03:09

Andrew Clark


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.

like image 45
Lachezar Avatar answered Sep 23 '22 03:09

Lachezar