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

3

5 Answers 5

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)
Sign up to request clarification or add additional context in comments.

3 Comments

True only for python2.
@Hyperboreus Also works in python3. dropbox.com/s/btdp3tw6035ylh4/…
range returns a list of integers in python3? Really?
2

This answer will help:

for x in reversed(range(5)):
    print x

Comments

0

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

for x in reversed(range(5)):
    print x

Comments

0
import random
l = range(0, 5) 
random.shuffle(l)
for count in l
    print count

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.