1

So let's just say I had code that went something like:

x = 'foobar'

and I wanted to print the first half (foo) and then the second (bar). One would think that it would either be written counting the first letter as "0" like the first item on a list -

x = 'foobar'
print x[0:2]
print x[3:5]

-or counting the first letter as "1" :

x = 'foobar'
print x[1:3]
print x[4:6]

But through a bit of trial-and-error, I've discovered that the first value (the one before the " : ") counts from 0, whereas the second value (the one after the " : ") counts from 1. So the
proper code would be:

x = 'foobar'
print x[0:3]
print x[3:6]

I get it now, but why is this? Is there some reason?

Charles Noon
  • 559
  • 3
  • 10
  • 16
  • Related : [The Python Slice Notation](http://stackoverflow.com/questions/509211/the-python-slice-notation), `x[1:3]` is equal to `x[1]+x[2]`, `3` is not inclusive. – Ashwini Chaudhary Jun 14 '13 at 08:22
  • the first argument is inclusive and the second is exclusive. if both were inclusive/exclusive you will not be able to select single characters or boundary characters – shyam Jun 14 '13 at 08:24
  • @shyam Wbu `x[1]` or `x[1:1]`, supposing both were inclusive? – Skamah One Jun 14 '13 at 08:31
  • @skamahone then I suppose that you have 2 representations for achieving the same thing making one of them redundant. So, I think it is designed like that to have more clarity of purpose – shyam Jun 14 '13 at 08:36
  • Note also: `for i in range(0,5): print i,` gives you `0 1 2 3 4`. – pfnuesel Jun 14 '13 at 08:56

3 Answers3

4

I understand why you are confused but it makes sense once you get used to it. I like to think of the numbers as the spaces between the elements where you are making the cut, if that makes sense.

      0 --- 1 --- 2 --- 3 --- 4 --- 5 --- 6
str = [  f     o     o     b     a     r  ]

           0 --- 1 --- 2 --- 3
str[0:3] = [  f     o     o  ]

           3 --- 4 --- 5 --- 6
str[3:6] = [  b     a     r  ]
nrob
  • 861
  • 1
  • 8
  • 22
1

Actually, the second element of the range points to element after that element we would like to extract from the str. Imagine that as for (i = 0; i < 3; ++i) ... if I can express that such way :-)

Michał Fita
  • 1,183
  • 1
  • 7
  • 24
  • @user2485209: It makes sense if you dig a little deeper. `x[:3]` (which is the same as `x[0:3]`) gives you 3 characters. `x[0:3] + x[3:6] + x[6:8]` gives you `x[0:8]`. `x[:-3] == x[:len(x)-3]`. – Petr Viktorin Jun 14 '13 at 08:47
  • 1
    @PetrViktorin Your explanation didn't really make any sense. – Skamah One Jun 14 '13 at 14:44
0

Perhaps it's best to think in mathematical notation:

x[a:b]
x[i], i ∈ [a, b)
x[i], a <= i < b

A negative number counts from the end, e.g:

x[-1]  # last element
x[:-1]  # all except last
x[1:-1]  # all except first and last

I hope this way of thinking helps a bit!

Dima Tisnek
  • 11,241
  • 4
  • 68
  • 120