Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
for n in range(x,y) ??
#1
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.
Reply
#2
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).
Reply
#3
Slicing and the range function has following rule:

Start is inclusive
Stop is exclusive
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  matplotlib x axis range goes over the set range Pedroski55 5 3,179 Nov-21-2021, 08:40 AM
Last Post: paul18fr
  Define a range, return all numbers of range that are NOT in csv data KiNeMs 18 7,024 Jan-24-2020, 06:19 AM
Last Post: KiNeMs

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020