Home > Blockchain >  Problem with negative step index in python
Problem with negative step index in python

Time:08-24

When we want to print reverse order of number using loops, for eg: 1 to 10 in reverse, we write the syntax as (10,0,-1), why don't we write it as (1,11,-1) ? Doesn't -1 already mean reverse, so why do we write 10,0 instead of 1,11 for range?

CodePudding user response:

The arguments for range in python are range(start, stop, step).

The start value is the first index (inclusive) of the range function. This defaults to 0. In your case, the start value is 10.

The stop value is the last index (exclusive) of the range function. This means that the index before this number will be the last number.

The step value is the change in index between each run. This defaults to 1, but in your case is -1.

This means that the order of execution in your example would be:

10 -> Start
9  -> Step (-1)
8  -> Step (-1)
7  -> Step (-1)
6  -> Step (-1)
5  -> Step (-1)
4  -> Step (-1)
3  -> Step (-1)
2  -> Step (-1)
1  -> Step (-1), Stop as next index would be 0

CodePudding user response:

Because Python reads your loop from the first argument until the last one. When you call:

for _ in range(10, 0, -1):

Python reads exactly like that:

  1. What element I`m going from?
  2. What element I`m going to?
  3. What is the step I`m going with?

Otherwise, your loop won`t do anything.

  • Related