python list index - an easy question

Peter Otten __peter__ at web.de
Sat Dec 17 15:00:05 EST 2016


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? By Python's convention, the
>     first element of a list is indexed as "0". Doesn't x[1:5] mean a
>     sub-list of x, indexed 1,2,3,4,5? If I am right, it should print
>     [2,3,4,5,6]. Why does it print only [2,3,4,5]?

Python uses half-open intervals, i. e. the first index is included, but the 
last index is not:

x[1:5] == [x[1], x[2], x[3], x[4]]

The advantage of this convention is that it allows easy splitting and length 
spefication.

>>> items
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

To swap the head and tail:

>>> gap = 5
>>> items[gap:] + items[:gap]
[50, 60, 70, 80, 90, 0, 10, 20, 30, 40]

To extract a stride of a given length:

>>> start = 2
>>> length = 3
>>> items[start: start + length]
[20, 30, 40]

The disadvantage is that not everybody follows this convention...



More information about the Python-list mailing list