Cropping lists#

A common task in Python is to crop out parts of lists and tuples, for example to access specific parts from lists.

Let’s start with a list of numbers

data = [34, 0, 65, 23, 51, 9, 50, 78, 34, 100]

We can determine how many elements are in data:

len(data)
10

As shown earlier, we can access specific elements by passing an index. Counting the element-index starts at 0.

data[0]
34
data[1]
0

We can also pass negative indices. This will access elements from the end of the list. The last element has index -1.

data[-1]
100
data[-2]
34

Selecting ranges in lists#

We can also generate a new list that contains the first three elements. Therefore, we pass a range in form [start:end]. The first element has index start and the last element of the new list will be just before end.

data
[34, 0, 65, 23, 51, 9, 50, 78, 34, 100]
data[0:2]
[34, 0]
data[0:3]
[34, 0, 65]
data[1:2]
[0]

Furthermore, we don’t have to specify either start or end if we want to select all entries in a list from the start or until the end.

data
[34, 0, 65, 23, 51, 9, 50, 78, 34, 100]
data[:2]
[34, 0]
data[:3]
[34, 0, 65]
data[2:]
[65, 23, 51, 9, 50, 78, 34, 100]
data[3:]
[23, 51, 9, 50, 78, 34, 100]

This also works with negative indices

data[-2:]
[34, 100]

Stepping over entries in lists#

The : can also be used to provide a step length using the syntax [start:end:step].

data
[34, 0, 65, 23, 51, 9, 50, 78, 34, 100]

For example we can select every seceond element starting at the first:

data[0:10:2]
[34, 65, 51, 50, 34]
data[::2]
[34, 65, 51, 50, 34]

We can also start at the second element (index 1):

data[1::2]
[0, 23, 9, 78, 100]

Tuples#

All the introduced concepts above also work with tuples

immutable_data = tuple(data)
immutable_data
(34, 0, 65, 23, 51, 9, 50, 78, 34, 100)
immutable_data[:5]
(34, 0, 65, 23, 51)

Exercise#

Please select the three numbers 23, 9 and 78 from data using a single python command similar to the commands shown above.