Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python range() with negative strides

Tags:

python-3.x

Is there a way of using the range() function with stride -1?

E.g. using range(10, -10) instead of the square-bracketed values below?

I.e the following line:

for y in range(10,-10)

Instead of

for y in [10,9,8,7,6,5,4,3,2,1,0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10]:

Obviously one could do this with another kind of loop more elegantly but the range() example would work much better for what I want.

like image 436
RobotMugabe Avatar asked Mar 28 '12 14:03

RobotMugabe


People also ask

Can range take negative?

No. Because the range formula subtracts the lowest number from the highest number, the range is always zero or a positive number.

Can a stride be negative?

When a negative stride is specified for a vector, the location specified for the vector is actually the location of the last element in the vector. In other words, the vector is in reverse order in the array: (xn, xn-1, …, x1).

How do you iterate negative numbers in Python?

Method: Print all the negative numbers using a single-line solution. Print all negative numbers using for loop. Define the start and end limits of the range. Iterate from start range to end range using for loop and check if num is less than 0.


3 Answers

You can specify the stride (including a negative stride) as the third argument, so

range(10,-11,-1) 

gives

[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10]  

In general, it doesn't cost anything to try. You can simply type this into the interpreter and see what it does.

This is all documented here as:

range(start, stop[, step]) 

but mostly I'd like to encourage you to play around and see what happens. As you can see, your intuition was spot on.

like image 134
Useless Avatar answered Sep 25 '22 14:09

Useless


Yes, by defining a step:

for i in range(10, -11, -1):
    print(i)
like image 25
Michael Foukarakis Avatar answered Sep 22 '22 14:09

Michael Foukarakis


In addition to the other good answers, there is an alternative:

for y in reversed(range(-10, 11)):

See the documentation for reversed().

like image 28
Nayuki Avatar answered Sep 22 '22 14:09

Nayuki