![]() |
VOOZH | about |
Backward iteration in Python is traversing a sequence (like list, string etc.) in reverse order, moving from the last element to the first. Python provides various methods for backward iteration, such as using negative indexing or employing built-in functions like reversed().
Use reversed() method when we simply need to loop backwards without modifying original sequence or there is no need to create a new reversed copy.
50 40 30 20 10
Let's explore more methods that helps to iterate backward on any iterable. Here are some common approaches:
Table of Content
range function is provided with three arguments(N, -1, -1). Use this method when we need to modify elements or access their indices.
n o h t y P
We can use slicing slicing notation [::-1] to reverse the order of elements in an iterable. This works for lists, tuples, and strings, but not for sets or dictionaries (since they are unordered).
5 4 3 2 1
Using a while loop provides you control over the iteration process. This is need to manually control the index and decrement the index during each iteration to traverse the it backward.
5 4 3 2 1