-3

I'm a bit confused about slicing a list and the numbering here.

Python tends to start from 0 instead of 1, and it's shown below to work in that way well enough. But if we're starting from 0, and going until 3, why am I not getting exam instead of exa? After all, 0 - 3 is 4 numbers.

>>> test = "example string"
>>> print test[:3]
exa
>>> print test[0:3]
exa
>>> print test[1:3]
xa
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
David Metcalfe
  • 2,237
  • 1
  • 31
  • 44
  • 2
    In Python the range is half-closed. test[0:3] means [0, 3) 3 is *not* included in the range. You can think of it as, "till the third character" :) – thefourtheye Feb 28 '14 at 06:06

2 Answers2

1

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.

Community
  • 1
  • 1
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
1

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.

sashkello
  • 17,306
  • 24
  • 81
  • 109