Skip to content
Related Articles
Open in App
Not now

Related Articles

Python | Alternate Rear iteration

Improve Article
Save Article
Like Article
  • Last Updated : 21 Feb, 2023
Improve Article
Save Article
Like Article

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 backwards in alternate way 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




# Python3 code to demonstrate
# Alternate Rear iteration
# using reversed()
 
# Initializing number from which
# iteration begins
N = 6
 
# using reversed() to perform the Alternate Rear iteration
print ("The reversed numbers are : ", end = "")
for num in reversed(range(0, N + 1, 2)) :
    print (num, end = " ")

Output : 

The reversed numbers are : 6 4 2 0 

Time complexity: O(N)
Auxiliary space: O(1)

Method #2 : Using range(N, -1, -2) This particular task can also be performed using the conventional range function which, if provided with the third argument performs the alternate skip and second argument is used to start from backwards. 

Python3




# Python3 code to demonstrate
# Alternate Rear iteration
# using range(N, -1, -2)
 
# Initializing number from which
# iteration begins
N = 6
 
# using reversed() to perform the Alternate Rear iteration
print ("The reversed numbers are : ", end = "")
for num in range(N, -1, -2) :
    print (num, end = " ")

Output : 

The reversed numbers are : 6 4 2 0 

Time complexity: O(N/2), where N is the value of the variable N.
Auxiliary space: O(1), as we are not using any additional data structure to store the values.


My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!