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]?

asked Oct 27, 2013 at 2:11
1
  • 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. Commented Oct 27, 2013 at 2:17

3 Answers 3

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).

answered Oct 27, 2013 at 2:17
Sign up to request clarification or add additional context in comments.

Comments

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

answered Oct 27, 2013 at 2:22

Comments

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.

answered Oct 27, 2013 at 2:13

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.