Using enumerate in reverse order in Python

avatar

Borislav Hadzhiev

Last updated: Aug 29, 2022

banner

Photo from Unsplash

Using enumerate in reverse order in Python #

To use the enumerate function in reverse order:

  1. Use the enumerate() function to get access to the index when iterating.
  2. Convert the enumerate object to a list and reverse the list.
  3. Use a for loop to iterate over the list in reverse order.
main.py
my_list = ['a', 'b', 'c', 'd', 'e'] # ✅ using enumerate in reverse order for index, item in reversed(list(enumerate(my_list))): print(index, item) # 👉️ 4 e 3 d 2 c 1 b 0 a # ------------------------------ # ✅ iterating over a list in reverse order for item in reversed(my_list): print(item) # 👉️ e d c b a

We used the reversed() function to iterate over an enumerate object in reverse.

The enumerate function takes an iterable and returns an enumerate object containing tuples where the first element is the index and the second is the item.

main.py
my_list = ['a', 'b', 'c', 'd', 'e'] for index, item in enumerate(my_list): print(index, item) # 👉️ 0 a, 1 b, 2 c, 3 d, 4 e

We used the list() class to convert the enumerate object to a list because the first argument the reversed() function takes is a sequence.

main.py
my_list = ['a', 'b', 'c', 'd', 'e'] # 👇️ [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e')] print(list(enumerate(my_list))) # 👇️ [(4, 'e'), (3, 'd'), (2, 'c'), (1, 'b'), (0, 'a')] print(list(reversed(list(enumerate(my_list)))))

The last step is to use a for loop to iterate over the list of tuples.

main.py
my_list = ['a', 'b', 'c', 'd', 'e'] # ✅ using enumerate in reverse order for index, item in reversed(list(enumerate(my_list))): print(index, item) # 👉️ 4 e, 3 d, 2 c, 1 b, 0 a
The first element in each tuple is the index and the second is the corresponding value.

If you only need to iterate over a list in reverse order and don't need access to the index, use the reversed() function directly.

main.py
my_list = ['a', 'b', 'c', 'd', 'e'] for item in reversed(my_list): print(item) # 👉️ e, d, c, b, a

The reversed function takes an iterator, reverses it and returns the result.

main.py
my_list = ['a', 'b', 'c', 'd', 'e'] # 👇️ ['e', 'd', 'c', 'b', 'a'] print(list(reversed(my_list)))
The reversed() function returns an iterator object. You can pass it to the list() class if you need to convert the object to a list.

However, if you only need to iterate over the list in reverse order, you can can do it directly.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.