0

The code shown below:

for count in range(0, 5):
    print(count)

The output will be:

0 1 2 3 4

The question is Is it possible to iterate in Python out of order:

Something like this:

for count in range(5, 0):
    print(count)

the output: 4 3 2 1 0

Mariusz Jamro
  • 30,615
  • 24
  • 120
  • 162
user1519221
  • 631
  • 5
  • 13
  • 24
  • 1
    if you ve time please read the usage of range, range([start,] stop[, step]) -> list of integers – James Sapam Dec 29 '13 at 15:22
  • Use `reversed(range(0,5))`. source: [http://stackoverflow.com/questions/7286365/print-a-list-in-reverse-order-with-range-in-python][1] [1]: http://stackoverflow.com/questions/7286365/print-a-list-in-reverse-order-with-range-in-python – OlivierH Dec 29 '13 at 15:23
  • by "out of order" , do you mean random ? – Arovit Dec 29 '13 at 15:36

5 Answers5

3

range(start, stop[, step])

It accepts the third parameter step

So you can do this way:

for count in range(4, -1, -1):
    print(count)
iMom0
  • 12,493
  • 3
  • 49
  • 61
2

This answer will help:

for x in reversed(range(5)):
    print x
Community
  • 1
  • 1
idanshmu
  • 5,061
  • 6
  • 46
  • 92
0

You can use reversed() to inverse the order of values in iterator:

for x in reversed(range(5)):
    print x
Mariusz Jamro
  • 30,615
  • 24
  • 120
  • 162
0
import random
l = range(0, 5) 
random.shuffle(l)
for count in l
    print count
vh5
  • 161
  • 3
0

RANGE produces APs(Arithmetic Progressions).
In this case the step size is negative.

You can specify step size by:

range(Start of series, End of series [, Step size])

Thus here we use:

for counter in range(4, -1, -1):
    print counter

End of series is always 1*(step size) less than the value passed to range.

NOTE:

reversed(range(...))

Can also be used, but its efficiency is lower compared to the above method.
Additionally many other manipulation functions do not work with reversed() yet.