Search code examples
pythonloopsfor-loopiterationdecrease-key

how to arrange an array in decreasing order


I have a simple code to iterate over all the elements within the range

for i in range(5,10):
    print(i)
#output
5
6
7
8
9

Now, would it be possible to iterate the same elements from 10 to 5 in the decreasing order ? By changing the range in the above code from 10 to 5 won't work

 for i in range(10,5):
        print(i)
    #output not printed and no error displayed

Solution

  • You can do something like

    for i in range(10,0,-1):
        print(i)
    

    The -1 here is saying that we are taking steps of -1 instead of the 1 that is default.