Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does range in python "stop short"?

Tags:

python

range

OK, teaching python to the kids. We just wrote our first little program:

b = 0
for a in range (1, 10)
    b = b + 1
    print a, b

Stops at 9, 9. They asked "why is that" and I can't say that I know the answer.

My code always involves files, and my "for row in reader" doesn't stop one line short, so I don't actually know. In mathematical notation, this behavior would be [1,10). Technically (1,10) would be 2,3,4,5,6,7,8,9, and indeed I want [1,10].

like image 733
Todd Curry Avatar asked May 18 '26 02:05

Todd Curry


1 Answers

It's just usually more useful than the alternatives.

  • range(10) returns exactly 10 items (if you want to repeat something 10 times)
  • range(10) returns exactly the indices in a list of 10 items
  • range(0, 5) + range(5, 10) == range(0, 10), which makes it easier to reason about ranges
like image 97
Pavel Anossov Avatar answered May 19 '26 15:05

Pavel Anossov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!