-1

In Python, I'm wondering why slices work the way they do. Why did Guido van Rossum define a[start:end] to include a[start] but not a[end], or as in the title, why does a[0:1] only contain the first element and not the first two?

This seems like a step back from MATLAB's indexing behavior.

EDIT: The reason I asked this question is that it is confusing that a[0:0] is empty. But I didn't design a popular language, so what do I know.

Andrew
  • 867
  • 7
  • 20
  • 1
    Because not including the end index fits neatly with 0-based indexing. `range(10)` produces the indices 0 through to 9, slicing with `sequence[:len(sequence)]` works, etc. – Martijn Pieters Jan 31 '14 at 13:46
  • I note that MATLAB uses 1-based indexing, which means that closed-end indexing makes some sense. You won't get the nice `a == a[:end] + a[end:]` invariant we have in Python in MATLAB, however. – Martijn Pieters Jan 31 '14 at 13:56

3 Answers3

5

To quote Guido van Rossum himself:

[...] I was swayed by the elegance of half-open intervals. Especially the invariant that when two slices are adjacent, the first slice's end index is the second slice's start index is just too beautiful to ignore. For example, suppose you split a string into three parts at indices i and j -- the parts would be a[:i], a[i:j], and a[j:].

Nigel Tufnel
  • 11,146
  • 4
  • 35
  • 31
0

a[start:end-1] allows you to use a[0:len(a)].

And it fits with all other functions such as range(), and others.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
1478963
  • 1,198
  • 4
  • 11
  • 25
  • Surely you would always use `[:]` in that scenario? But the point about using `len(a)` as `stop` is valid, e.g. for `range`. – jonrsharpe Jan 31 '14 at 13:47
  • @jonrsharpe You are correct, but this is just an example that is easy for him to understand. – 1478963 Jan 31 '14 at 13:50
0

Python indexing is 0-based. By excluding the end value, most slicing and range() operations can naturally reflect the number of items sliced or produced while still including index 0.

Thus, range(10) produces 10 elements, from 0 through to 9. Slicing to with sequence[:1] produces 1 element, index 0.

Moreover, not including the end index makes it easier to use the same value as a start for a next section. Thus sequence[:i] + sequence[i:] re-creates sequence from two slices without having to adjust i.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343