Slicing lists

Recall that we can create lists using range as follows:

In [1]:
list(range(5, 10, 2))
Out[1]:
[5, 7, 9]

The values of list(range(5, 10, 2)) is a list ranging from 5 to 10 (not including anything $\geq 10$, increasing in steps of 2.

Here is how we can access lists in a similar way. What follows is usually called "slicing".

L[m:n:k] means "get the entries of L, starting with index m and up (if $k\geq 0$)/down (if $k<0$) to but not including index n, with steps of k".

In [2]:
L = [9, 8, 7, 6, 5, 4, 3, 10, 15, 17, 18]
In [3]:
L[1:8:2]
Out[3]:
[8, 6, 4, 10]
In [4]:
L[9:3:-1]
Out[4]:
[17, 15, 10, 3, 4, 5]

It is possible to omit the step size. The default is 1:

In [5]:
L[1:8]
Out[5]:
[8, 7, 6, 5, 4, 3, 10]

It's also possible to omit the start and end points. They are determined according to the sign of the step size:

In [6]:
L[5::1]
Out[6]:
[4, 3, 10, 15, 17, 18]
In [7]:
L[5:]  #omit end point and step size
Out[7]:
[4, 3, 10, 15, 17, 18]
In [8]:
L[5::-1]   #end point is the beginning since the step size is negative
Out[8]:
[4, 5, 6, 7, 8, 9]

One common thing that people do is obtain a copy of the list in reverse by only specifying that the step size is -1. That makes the starting point the very end of the list, and the end point the very beginning:

In [9]:
L
Out[9]:
[9, 8, 7, 6, 5, 4, 3, 10, 15, 17, 18]
In [10]:
L[::-1]
Out[10]:
[18, 17, 15, 10, 3, 4, 5, 6, 7, 8, 9]