elgnoh
elgnoh

Reputation: 523

Confusion about Python list slice results

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

Upvotes: 3

Views: 770

Answers (4)

user1277476
user1277476

Reputation: 2909

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.

Upvotes: 0

Levon
Levon

Reputation: 143152

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.

Upvotes: 9

istruble
istruble

Reputation: 13722

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] 

Upvotes: 1

darkphoenix
darkphoenix

Reputation: 2167

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

Upvotes: 1

Related Questions