Daming Lu
Daming Lu

Reputation: 376

What is the best way in Python to loop over a list back to front?

Right now I do it like this:

for i in range(len(my_list)-1, -1, -1):
    # ...

but I am wondering if we have a better way with clearer meaning.

Upvotes: 1

Views: 10642

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121992

Use the reversed() function:

for elem in reversed(my_list):

An object can support efficient reverse iteration by offering a __reversed__() special method; list objects implement this method to support reverse iteration efficiently. Otherwise, the normal sequence protocol (object.__getitem__() and object.__len__()) must be implemented.

Note that this doesn't create a new list object; it produces an iterator, an object that tracks position in the list as you loop over it.

Upvotes: 8

Related Questions