Why is this list slice treating 0 and 1 as the same in Python? [duplicate]

落爺英雄遲暮 提交于 2019-12-02 14:55:33

This is an intentional way, last element is exclusive.

Why is it so?

Firstly, my understanding it is because test[0:len(test)] should print all the list and then test[0:len(test)-1] excludes one element. This is prettier and more readable than if the last element would be included.

Secondly, it is because if you have test[:-1] it will return all the elements, but the last, which is very intuitive. If it would include the second index, to cut the last element you'd have to do test[:-2] which is ugly and makes it harder to read...

Also, length of your resulting list is end - start, which is yet another convenient feature about it.

Christian

If you have

text[0:3]

it will return elements from 0 to 3 - 1.

text[0]
text[1]
text[2]

not

text[3]

In general, it will return values from start to end - 1. For further information, you could read this.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!