Why does range(start, end) not include end?

后端 未结 9 1198
夕颜
夕颜 2020-11-22 10:24
>>> range(1,11)

gives you

[1,2,3,4,5,6,7,8,9,10]

Why not 1-11?

Did they just decide to do it lik

9条回答
  •  囚心锁ツ
    2020-11-22 11:11

    It's also useful for splitting ranges; range(a,b) can be split into range(a, x) and range(x, b), whereas with inclusive range you would write either x-1 or x+1. While you rarely need to split ranges, you do tend to split lists quite often, which is one of the reasons slicing a list l[a:b] includes the a-th element but not the b-th. Then range having the same property makes it nicely consistent.

提交回复
热议问题