Cropping lists
Contents
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 = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
We can determine how many elements are in data
:
len(data)
9
As shown earlier, we can access specific elements by passing an index. Counting the element-index starts at 0.
data[0]
'A'
data[1]
'B'
We can also pass negative indices. This will access elements from the end of the list. The last element has index -1.
data[-1]
'I'
data[-2]
'H'
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
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
data[0:2]
['A', 'B']
data[0:3]
['A', 'B', 'C']
data[1:2]
['B']
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
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
data[:2]
['A', 'B']
data[:3]
['A', 'B', 'C']
data[2:]
['C', 'D', 'E', 'F', 'G', 'H', 'I']
data[3:]
['D', 'E', 'F', 'G', 'H', 'I']
This also works with negative indices
data[-2:]
['H', 'I']
data[:-2]
['A', 'B', 'C', 'D', 'E', 'F', 'G']
data[-7:-5]
['C', 'D']
data[-5:-7]
[]
Tuples#
All the introduced concepts above also work with tuples
immutable_data = tuple(data)
immutable_data
('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I')
immutable_data[:5]
('A', 'B', 'C', 'D', 'E')
Exercises#
Please print out the seond-last character in data
.
Create a string of your name and crop the first and last name from this string. Hint: You can access strings in multiple ways, e.g. some_string[0:10]
or you could use a built-in function, such as some_string.split()