'Range function with step higher than stop

Could someone explain me why the output is 22 here:

def fun():
    for x in range(22,23,24):
        print(x)
fun()


Solution 1:[1]

The syntax for range is range(start, stop, step)

The range of numbers to be printed starts from 22, to 23 (end point not included), in steps of 24.

The first number is 22, which gets printed.

The next number will be 22 + 24 = 46, which is greater than 23, so it doesn’t get printed and the loop terminates.

Solution 2:[2]

You are iterating over a range which starts with 22, ends before 23, and makes steps of 24.


To better understand what you are doing, try this:

>>> list(range(22,23,24))
[22]

You are starting from 22, then doing a step of 24, and you clearly exceeded the limit of 23 since you are at 46 with 22+24.


I would suggest to read the documentation about range's constructor.

range(start, stop[, step]) # This is the prototype of the constructor

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Deepthi Tabitha Bennet
Solution 2