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

后端 未结 9 1187
夕颜
夕颜 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:18

    It works well in combination with zero-based indexing and len(). For example, if you have 10 items in a list x, they are numbered 0-9. range(len(x)) gives you 0-9.

    Of course, people will tell you it's more Pythonic to do for item in x or for index, item in enumerate(x) rather than for i in range(len(x)).

    Slicing works that way too: foo[1:4] is items 1-3 of foo (keeping in mind that item 1 is actually the second item due to the zero-based indexing). For consistency, they should both work the same way.

    I think of it as: "the first number you want, followed by the first number you don't want." If you want 1-10, the first number you don't want is 11, so it's range(1, 11).

    If it becomes cumbersome in a particular application, it's easy enough to write a little helper function that adds 1 to the ending index and calls range().

提交回复
热议问题