Python | Alternate Rear iteration
Last Updated :
16 May, 2023
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
N = 6
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
N = 6
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.
Method 3: use list comprehension
Python3
N = 6
nums = [ str (num) for num in range (N, - 1 , - 2 )]
result = " " .join(nums)
print ( "The reversed numbers are:" , result)
|
Output
The reversed numbers are: 6 4 2 0
Time complexity: O(N/2) for generating the list and O(N) for joining the elements,
Auxiliary space: O(N) for storing the list. However, it may be slightly less efficient than the other methods due to the overhead of creating and joining a list.
Method 4: Using a while loop
Step-by-step approach:
- Initialize a variable num to N.
- While num is greater than or equal to 0, print its value and decrement it by 2.
- Repeat step 2 until num becomes less than 0
- Print a newline character to end the output.
Python3
N = 6
print ( "The numbers are: " , end = "")
num = N
while num > = 0 :
print (num, end = " " )
num - = 2
print ()
|
Output
The numbers are: 6 4 2 0
Time Complexity: O(N/2), as we iterate through N/2 numbers, where N is the starting number.
Auxiliary Space: O(1), as we only use a constant amount of extra memory to store the num variable.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...