Home > Back-end >  how to arrange an array in decreasing order
how to arrange an array in decreasing order

Time:05-21

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

CodePudding user response:

Try this,

for i in range(9,4,-1):  #decreament 9 to 4
     print(i)
#output
9
8
7
6
5

Here 9 is starting vale 4 is ending value -1 is step value

CodePudding user response:

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.

CodePudding user response:

You can use reversed builtin method

for i in reversed(range(5, 10)):
    print(i)

An other option is to set step in range loop like range(10, 5, -1)

  • Related