Learn
Working with Lists in Python
Slicing Lists
Suppose we have a list of letters:
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
Suppose we want to select from b
through f
.
We can do this using the following syntax: letters[start:end]
, where:
start
is the index of the first element that we want to include in our selection. In this case, we want to start atb
, which has index1
.end
is the index of one more than the last index that we want to include. The last element we want isf
, which has index5
, soend
needs to be6
.
This example would yield:sublist = letters[1:6] print(sublist)
Notice that the element at index['b', 'c', 'd', 'e', 'f']6
(which isg
) is not included in our selection.
Creating a selection from a list is called slicing.
Instructions
1.
Use print
to examine the variable beginning
.
How many elements does it contain?
2.
Modify beginning
, so that it selects the first 4 elements of suitcase
.
3.
Create a new list called middle
that contains the middle two items from suitcase
.