Python range() with negative strides

前端 未结 7 974

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?

<
相关标签:
7条回答
  • 2020-12-09 15:32

    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.

    0 讨论(0)
提交回复
热议问题