In Python, often we want to extract only a portion of a list. Dividing a list in such a manner is referred to as slicing.
Lets assume we have a list of
letters = ["a", "b", "c", "d", "e", "f", "g"]
Suppose we want to select from
We can do this using the following syntax:
startis the index of the first element that we want to include in our selection. In this case, we want to start at
"b", which has index
endis the index of one more than the last index that we want to include. The last element we want is
"f", which has index
endneeds to be
sliced_list = letters[1:6] print(sliced_list)
["b", "c", "d", "e", "f"]
Notice that the element at index
6 (which is
"g") is not included in our selection.
print() to examine the variable
Before hitting Run think about what elements
beginning will contain?
beginning, so that it selects the first 2 elements of
Create a new list called
middle that contains the middle two items (
["pants", "pants"] ) from
middle to see the slice!