3

This line of code

print [0, 1, 2, 3, 4][0:1:1]

returns [0].

However, the following line of code:

print [0, 1, 2, 3, 4][0:0:1]

returns [].

Why is this? Based on this Explain Python's slice notation, my understanding is that the format should be:

a[start:end:step] # start through not past end, by step

So shouldn't [0, 1, 2, 3, 4][0:0:1] start and end at the 0th value, thus returning [0]?

Community
  • 1
  • 1
Lukas Halim
  • 535
  • 1
  • 7
  • 12
  • 7
    `not past end` is incorrect - `up to (but not including) end` is correct. Python slices are inclusive at the `start` end but exclusive at the `end` end. – Tim Peters Oct 27 '13 at 02:17

3 Answers3

6

The "end" index of a slice is always excluded from the result; i.e., listy[start:end] returns all listy[i] where start <= i < end (note use of < instead of <=). As there is no number i such that 0 <= i < 0, listy[0:0:anything] will always be an empty list (or error).

jwodder
  • 54,758
  • 12
  • 108
  • 124
2

The end index in Python's slice notation is exclusive. A slice of [n:m] will return every element whose index is >= n and < m.

To simplify things a bit, try it without the step (which isn't necessary when the step value is 1):

>>> a = [0, 1, 2, 3, 4]
>>> a[0:1]
[0]
>>> a[0:0]
[]

As a general rule, the number of elements in a slice is equal to the slice's start index minus the slice's end index. I.e., the slice [n:m] will return m-n elements. This agrees with the one element (1-0) returned by [0:1] and zero elements (0-0) returned by [0:0].

(Note that this is not true if either of the slice indices is outside of the size of the array.)

For a nice visualization of how slice indices work, search for "One way to remember how slices work" at http://docs.python.org/2/tutorial/introduction.html

dbort
  • 962
  • 8
  • 15
1

Note that is [0:0:1] not [0:1:1]

So:

start = 0
end = 0
step = 1

The slice [start:end:step] means it will return values that are between start and end - 1 with a certain step, so for your example:

...[0:0:1]

Values between 0 and -1, so it doesn't return anything.

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