Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Traverse a list in reverse order in Python

So I can start from collection[len(collection)-1] and end in collection[0].

I also want to be able to access the loop index.

like image 259
Joan Venge Avatar asked Feb 09 '09 19:02

Joan Venge


People also ask

How do I reverse the order of a traverse list in Python?

Use the reversed() Function to Traverse a List in Reverse Order in Python. We can traverse a list in Python in reverse order by using the inbuilt reversed() function available. The reversed() function returns the reversed iteration of the sequence provided as input.

How do you reverse a list in a for loop in Python?

Python comes with a number of methods and functions that allow you to reverse a list, either directly or by iterating over the list object. You'll learn how to reverse a Python list by using the reversed() function, the . reverse() method, list indexing, for loops, list comprehensions, and the slice method.


2 Answers

You can do:

for item in my_list[::-1]:     print item 

(Or whatever you want to do in the for loop.)

The [::-1] slice reverses the list in the for loop (but won't actually modify your list "permanently").

like image 42
mipadi Avatar answered Sep 22 '22 05:09

mipadi


Use the built-in reversed() function:

>>> a = ["foo", "bar", "baz"] >>> for i in reversed(a): ...     print(i) ...  baz bar foo 

To also access the original index, use enumerate() on your list before passing it to reversed():

>>> for i, e in reversed(list(enumerate(a))): ...     print(i, e) ...  2 baz 1 bar 0 foo 

Since enumerate() returns a generator and generators can't be reversed, you need to convert it to a list first.

like image 173
Greg Hewgill Avatar answered Sep 24 '22 05:09

Greg Hewgill