# python list index - an easy question

Terry Reedy tjreedy at udel.edu
Sat Dec 17 17:18:31 EST 2016

```On 12/17/2016 2:10 PM, John wrote:
> Hi,
>
>    I am new to Python, and I believe it's an easy question. I know R and Matlab.
>
> ************
>>>> x=[1,2,3,4,5,6,7]
>>>> x[0]
> 1
>>>> x[1:5]
> [2, 3, 4, 5]
> *************
>
>     My question is: what does x[1:5] mean?

The subsequence between slice positions 1 and 5, length 5-1=4.
Slice positions are before and after each item, not through them.
There are n+1 slice positions for n items: 0 before the first,
1 to n-1 between pairs, and n after the last.
Think of slice positions as tick marks on a line with the length 1
segment between as a cell holding a reference to one item.

a b c d e
+-+-+-+-+-+
0 1 2 3 4 5

Slice 1:4 of length 3 is sequence with b, c, d.
Slice 3:3 of length 0 is an empty sequence.

> By Python's convention, the first element of a list is indexed as "0".

Think of 0 as .5 rounded down, or represent by the lower bound.
Other language round up to 1, or use the upper bound.

> Doesn't x[1:5] mean a sub-list of x, indexed 1,2,3,4,5?

No.  It is items between 1:2, 2:3, 3:4, 4:5.

Terry Jan Reedy

```