Backward iteration in Python
The iteration of numbers is done by looping techniques in Python. There are many techniques in Python which facilitate looping. Sometimes we require to perform the looping backward and having shorthands to do so can be quite useful. Let’s discuss certain ways in which this can be done.
Method #1 : Using reversed()
The simplest way to perform this is to use the reversed function for the for loop and the iteration will start occurring from the rear side than the conventional counting.
# Python3 code to demonstrate # backward iteration # using reversed() # Initializing number from which # iteration begins N = 6 # using reversed() to perform the back iteration print ("The reversed numbers are : ", end = "") for num in reversed(range(N + 1)) : print (num, end = " ") |
The reversed numbers are : 6 5 4 3 2 1 0
Method #2 : Using range(N, -1, -1)
This particular task can also be performed using the conventional range function which, if provided with the third argument performs the skip and second argument is used to start from backwards.
# Python3 code to demonstrate # backward iteration # using range(N, -1, -1) # Initializing number from which # iteration begins N = 6 # using reversed() to perform the back iteration print ("The reversed numbers are : ", end = "") for num in range(N, -1, -1) : print (num, end = " ") |
The reversed numbers are : 6 5 4 3 2 1 0
Recommended Posts:
- Python | Pair iteration in list
- Python | Index specific cyclic iteration in list
- Reading Python File-Like Objects from C | Python
- Python | Convert list to Python array
- Python | Index of Non-Zero elements in Python list
- Important differences between Python 2.x and Python 3.x with examples
- Python | Merge Python key values to list
- Python | Add Logging to Python Libraries
- Python | Sort Python Dictionaries by Key or Value
- Python | Add Logging to a Python Script
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Visualizing O(n) using Python
- JavaScript vs Python : Can Python Overtop JavaScript by 2020?
- max() and min() in Python
- Python | a += b is not always a = a + b
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



