0

I just started to learn python and I've comes to slices of strings.

When I type

suitcase = ["sunglasses", "hat", "passport", "laptop", "suit", "shoes"]
print suitcase[0:1]

I expect it to print ['sunglasses', 'hat], but I get ['sunglasses']. From what I've read it's aList[beginIndex:endIndex], but from my experience it's more like aList[beginIndex:endIndex+1] to get the index you which to have last.

Can someone explain why it's like this? I can't understand the reasoning behind it.

BlackVoid
  • 627
  • 1
  • 6
  • 21
  • 1
    how would you expect to select the first elem then? I think this is pretty much the reasoning. – root Apr 09 '13 at 19:14

3 Answers3

2

From the docs: "The slice of s from i to j is defined as the sequence of items with index k such that i <= k < j."

wRAR
  • 25,009
  • 4
  • 84
  • 97
2

The best argument in my opinion is that you can get the number of elements returned by the slice using endIndex - startIndex.

This is also closely related to the built-in range() function. If two arguments are used they are interpreted as a start and stop index, but if only one is used then it is the stop index and the start index is set to 0. So range(5) gives a list with 5 elements. If slices worked they way you think they should then range() would probably have the same behavior, and range(5) returning 6 elements would be pretty confusing.

Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
0

Slices in Python are defined as inclusive/exclusive, i.e., the first item you want, followed by the first item you don't want.

I don't know specifically why they did it this way, but it's consistent with how range() works, and also works well with len() (that is, a slice of a whole container x is [0:len(x)]); this also plays well with negative slices: x[-1] is x[len(x)-1].

kindall
  • 178,883
  • 35
  • 278
  • 309