Backward iteration in Python program

PythonServer Side ProgrammingProgramming

In this tutorial, we are going to see the backward iteration. In most of the cases, we use normal iteration. Knowing about the backward iteration is a plus point in some cases. We will use range() function to iterate in a backward direction. Let's see what is a range() first.

range()

range() has a wide range of uses. We can use it with numbers, iterables, etc.. Here, we are talking about the numbers.

It takes at most three arguments. It has three cases.

  • If you pass only one argument, then it takes that argument as an upper bound and defaults lower bound is zero. And the default increment value is one.

  • If you pass two arguments, then it takes the first argument as a lower bound and second argument as an upper bound. And the default increment value is one.

  • If you pass three arguments, then it takes the first argument as a lower bound, second argument as an upper bound and third argument as increment value.

We are going to use three arguments for the backward iteration.

Example

# loop which iterates from 10 to 0
# range(lower bound, upper bound, increment value)
for i in range(10, -1, -1):
   # printing the value
   print(i)

Output

If you run the above program, you will get the following results.

10
9
8
7
6
5
4
3
2
1
0

Example

Iterating from backward in an iterable.

# initialising an iterable
nums = ['Hafeez', 'Aslan', 'Kareem']
# writing a loop which prints list items from the end
for i in range(len(nums) - 1, -1, -1):
   # printing the list item
   print(nums[i])

Output

If you run the above program, you will get the following results.

Kareem
Aslan
Hafeez

Conclusion

If you have any queries in the tutorial, ask them in the comment section.

raja
Published on 01-Nov-2019 12:43:52
Advertisements