Backward iteration in Python (original) (raw)

Last Updated : 20 Nov, 2024

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().

Using reversed() method

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.

Python `

a = [10, 20, 30, 40, 50]

#Loop through the list #using reversed() to reverse the order of list for b in reversed(a): print(b)

`

Let’s explore more methods that helps to iterate backward on any iterable. Here are some common approaches:

Table of Content

Using range(N, -1, -1)

range function is provided with three arguments(N, -1, -1). Use this method when we need to modify elements or access their indices.

Python `

s = "Python"

- len(s) - 1: Start at the last index

- -1: Ensures the loop stops after the first character

- -1: The step value to iterate backwards

for i in range(len(s) - 1, -1, -1): print(s[i])

`

**Using Slicing [::-1]

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).

Python `

a = [1, 2, 3, 4, 5]

#Loop through the List

reverse order using slicing(::-1)

for item in a[::-1]: print(item)

same logic written using List comprehension

[print(item) for item in a[::-1]]

`

Using a While Loop

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.

Python `

a = [1, 2, 3, 4, 5]

i = len(a) - 1

Start a while loop that continues

until as 'i' is greater than or equal to 0

while i >= 0: print(a[i]) i -= 1

`