0
Q:

python for loop backwards

# 1.
for i in reversed(range(3)): # output: 	0
    print(i)				 #			1
    						 # 			2
# works with arrays as well , reversed(arr)

# 2.
# another alternative is
arr = [1,2,3]
# note: arr[start : end : step]
for i in arr[::-1]:			 # output:	0
  print(i)					 # 			1
  							 #			2

# 3.
# last alternative i don't recommened!
# note: range(start, end, step)
for i in range(len(arr) - 1, -1 , -1): 	# output: 	0
  print(i)								# 			1
  										# 			2
# read more on range() to understand even better how it works has the same rules as the arrays
5
    for i in range(len(item)-1, -1, -1):
        print(item[i])
4
# 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 = " ") 
0

New to Communities?

Join the community