manyspikes

Slicing

Initialising environment...

Now let's say we would like to access not just one value, but a subset of contiguous values in a list or tuple. This is called slicing.

To slice a sequence, you use the variable name followed by [start:end], where start is the start index and end is the end index.

data = (4.2, 1.3, 6.6, 2.0, 8.1) start = 1 end = start + 3 middle_values = data[start:end] print(middle_values)

The snippet above would print (1.3, 6.6, 2.0).

Notice how the value of the end index, in this case 4, does not returned in the result. When you specify a slice, the start value is included but the end value is excluded from the result.

If you want to slice beginning at the start of a sequence, you can ommit the start value and just write data[:end].

Similarly, if you want to slice to the end of the sequence, you can ommit the end value and just write data[start:].

Above we demonstrate slicing in tuples, but it works similarly in lists.

Instructions

Create a list holding 10 elements and assign it to the variable data (the values can be whatever you would like, as long as they are all different).

Using slicing, extract the sixth, seventh and eighth values from data and assign the to a variable called values.