Python Forum

Full Version: for n in range(x,y) ??
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Why does
>> for n in range(1,5)
give 4 iterations?

>> for n in range(0,5)
give 4 iterations?

>> for n in tange(1,6)
give 5 iterations?

Surely this makes little sense. Do I need to set a base number somewhere like you used to have to in Basic many years ago?

Thanks.
The iterator returned by range() starts at either 0 or the start number provided. It stops when the index equals the end number.

for n in range(1,5):
    print(n)

# is equivalent to 

n = 1
while 1 <= n < 5:
    print(n)
    n += 1
range(0,5) returns five iterations from 0 through 4. A common way of returning the end number of a range is to increase the end number by 1; instead of range(0,5), use range(0,6).
Slicing and the range function has following rule:

Start is inclusive
Stop is exclusive