-1

In Python For loop, the last index value is not processed. Why?

to=np.shape(aStaffs)[0]-1   # gives 4 (5 items, but I do not use index 0)
print("to:",to,"  ",end=" ")

for stf in range(1,to,1):
    print("stf:",stf,"  ",end=" ")  
# BUT stf only gives, 1,2,3, not 4
Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
  • The for loop isn't doing anything funny. The `range` object specifies a _semi-open_ interval `[start, stop)`. The `stop` value is not included in the range – Pranav Hosangadi Feb 22 '23 at 04:11
  • Does this answer your question? [Why does range(start, end) not include end?](https://stackoverflow.com/questions/4504662/why-does-rangestart-end-not-include-end) – Pranav Hosangadi Feb 22 '23 at 04:12

1 Answers1

0

The range function returns a half-open interval, meaning either the start value or the stop value is included but not both. The range() documentation says,

For a positive step, the contents of a range r are determined by the formula r[i] = start + step*i where i >= 0 and r[i] < stop.

You can get the range to include the last index value by incrementing your stop parameter: range(1,to+1,1).

iforapsy
  • 302
  • 2
  • 5
  • But when I add+1, I get an overindex error. So, it was unsolvable. For now I switched on a While loop. I'll take your answer into account. . Thanks. – Marc Tetreault Feb 23 '23 at 13:06