What happens when my Python range object stop value is never hit?

Issue

I’m learning python and I have a little snippet that is shown below:

for i in range(-10, 11, -6):
    print(i)

This did not throw up an error nor give an output. Surprisingly I expected an error, since that stop value of 11 would never be hit. Any ideas why that is?

Solution

Range represents an immutable sequence of numbers.

Here is a documentation of range type.

In your case:

  1. start = -10
  2. stop = 11
  3. step = -6

For a negative step, the contents of the range are still determined by the formula r[i] = start + step*i, but the constraints are i >= 0 and r[i] > stop.

A range object will be empty if r[0] does not meet the value constraint.

so let’s try to generate range first element for your case

r[0] = -10 + -6 * 0
r[0] = -10

but -10 is less than stop so algorithm stops here producing an empty range

>>> range(-10, 11, -6)
[]

so in your code range will be equivalent to this:

for i in []:  # empty array, 0 iterations of loop, nothing printed to console
    print(i)

and this code is perfectly valid python, "iterate over an empty range and finish" – that is why (1) nothing printed as range is empty, and (2) you got no error as code is valid

Answered By – Piotr Szyma

Answer Checked By – Terry (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.