3

I'm new to Python, the following output I'm getting from a simple list slice operation confused the jebuse out of me.

Here is the code.

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

>>> a[3]
4

shouldn't a[1:3] returns [2,3,4] instead of [2,3]?

4 Answers 4

9

a[1:3] specifies a half-closed interval, which means it includes the values starting at the 1st specified index up to, but not including, at the 2nd index.

So in this case a[1:3] means the slice includes a[1] and a[2], but not a[3]

You see the same in the use of the range() function. For instance

 range(1, 5)

will generate a list from 1 to 4, but will not include 5.

This is pretty consistent with how things are done in many programming languages.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks for editing it to make to make it clearer, though i don't know what you mean by 'a half interval'
@darkphoenix half-closed interval means that the range includes only one of the values, and not the other. In math notation we'd write this as [1, 5) to mean 1, 2, 3, 4, whereas [1, 5] is 1, 2, 3, 4, 5 (if I remember my math notation correctly .. it's been a while :) .. see also this: mathworld.wolfram.com/Half-ClosedInterval.html
1

Slicing returns up to (but not including) the second slice index.

Comments

1

The docs for slice may help.

slice([start], stop[, step])
Return a slice object representing the set of indices specified by range(start, stop, step).

The slice format that most of are familiar with is just a shorthand:

a[start:stop:step] 

Comments

0

You've got some good answers about how it works, here's one with why:

a = '0123456789' a[2:4] '23' a[4:6] '45' a[6:8] '67'

IOW, it makes it easy to step through a list or string or tuple n characters at a time, without wasting time on the +1 / -1 stuff needed in most languages.

Comments

Your Answer

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.