Indexing and slicing of sequences#
A common task in Python is to crop out parts of lists or tuples, for example, to access specific elements. For this, we can use two approaches called indexing and slicing.
Let’s define a small list again:
data = [34, 0, 65, 23, 51, 9, 50, 78, 34, 100]
We can determine how many elements there are:
len(data)
10
Select an element via indexing#
As shown earlier, we can access specific elements by passing an index. Counting the element-index starts at 0.
data[0]
34
data[5]
9
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
Select a range via slicing#
We can also generate a slice of the list containing a certain number of elements by introducing the :
operator. With this, we pass a range in form [start:end:step]
, where step
is an optional parameter. Be aware, that the provided index at end
is not inclusive.
data
[34, 0, 65, 23, 51, 9, 50, 78, 34, 100]
# Slice with elements from index 1 to 5
data[1:6]
[0, 65, 23, 51, 9]
# slice with the first 3 elements
data[:3]
[34, 0, 65]
# slice with every second element, starting with the first one
data[::2]
[34, 65, 51, 50, 34]
Tuples and strings#
Indexing and slicing work the same way with the other sequence types, tuples and strings.
immutable_data = tuple(data)
immutable_data
(34, 0, 65, 23, 51, 9, 50, 78, 34, 100)
immutable_data[:5]
(34, 0, 65, 23, 51)
hello = "hello world"
hello
'hello world'
hello[0]
'h'
Exercise#
Please select the three numbers 23, 9 and 78 from data
using a single python command similar to the commands shown above.
Also, please select the word world
from hello
.