Python: Traverse List Backwards


If you want to traverse a list in Python backward, i.e. from the reverse direction (right-to-left) then you can make use of the built-in function reversed()


Example 1: With Numbers

numbers_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

for num in reversed(numbers_list):
    print(num, end=" ")
Output:

10 9 8 7 6 5 4 3 2 1



Example 2: With Strings

alphabets_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

for alphabet in reversed(alphabets_list):
    print(alphabet, end=" ")
Output:

j i h g f e d c b a

Python Iterate List in Reverse Order Example

Reference:

"Return a reverse iterator. seq must be an object which has a __reversed__() method or supports the sequence protocol (the __len__() method and the __getitem__() method with integer arguments starting at 0)."

Link: https://docs.python.org/3/library/functions.html#reversed

-

Facing issues? Have Questions? Post them here! I am happy to answer!


Author: Rakesh
Author Info:

Rakesh is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X





























Copyright © Code2care 2023 | Privacy Policy | About Us | Contact Us | Sitemap