Data Structures · Lists · lesson 2 of 10
Slicing
about 12 minutes · free · runs in your browser
Step 1 of 2
Taking a piece
A slice gives you a new list containing part of the original:
numbers = [0, 1, 2, 3, 4, 5]
numbers[1:4] # [1, 2, 3]
Read [start:stop] as "from start, up to but not including stop" — the same rule as
range(). A slice of [1:4] gives you three items, because 4 − 1 is 3.
Either end can be left out:
numbers[:3] # [0, 1, 2] — from the beginning
numbers[3:] # [3, 4, 5] — to the end
numbers[:] # a copy of the whole list
A third number is the step, and [::-1] is the idiomatic way to reverse:
numbers[::2] # [0, 2, 4]
numbers[::-1] # [5, 4, 3, 2, 1, 0]
Slicing works on strings too, and never raises IndexError — an out-of-range slice just
gives you less.
Your turn: take the first three, the last two, and a reversed copy.
You start from this, and edit it in the browser:
letters = ["a", "b", "c", "d", "e", "f"]
# Set first_three, last_two and reversed_letters.
Step 2 of 2
Slicing in a function
Slices are the tidiest way to answer "the middle bit" questions without index arithmetic scattered through your code.
Your turn: write middle(items) returning everything except the first and last
items. For a list of two or fewer, return an empty list.
You start from this, and edit it in the browser:
def middle(items):
# Return everything except the first and last item.
pass