Python List Slicing, + and *: Build New Lists
A slice like scores[1:3] copies part of a list. + joins lists and *
repeats one. All three build a new list and leave the old one unchanged.
Read Lists first: this lesson assumes indexing, len() and
.append().
Take part of a list with a slice
list[start:stop] takes the items from start up to, but not including, stop.
scores = [9, 7, 5, 3]
print(scores[1:3])
print(scores[:2])
print(scores[2:])
print(scores[-2:])
Leave out start to begin at 0. Leave out stop to run to the end.
scores[-2:] is the last two items.
Slices never go out of range
An index past the end raises an error. A slice past the end just stops early.
scores = [9, 7, 5, 3]
print(scores[1:10])
print(scores[10:])
print(scores[10]) # this line raises IndexError
So a slice is safe when you don't know the length: scores[:3] gives at most
three items, even from a shorter list.
Join with +, repeat with *
+ puts two lists end to end. * repeats a list a whole number of times.
first = [1, 2]
second = [3, 4]
both = first + second
print(both)
print(first)
print([0] * 4)
first is unchanged. Use .append() to add one item to the existing list;
use + when you want a new, combined list.
A slice is a copy, a name is not
b = a gives the same list a second name. b = a[:] makes a copy.
a = [1, 2, 3]
same = a
copy = a[:]
a.append(4)
print(same)
print(copy)
same sees the new 4 because it is the same list. copy does not.
Note: a slice copies only the outer list. Lists inside it are still shared.
See also: List methods, String indexing.
Your turn
Build podium from the first three of ranked, then rest from everything
after them. Print podium, rest, and podium + rest to show nothing was lost.
ranked = ["Mia", "Leo", "Ada", "Sam", "Kai"]
# add five lines: make podium and rest with slices, then print podium, rest and podium + rest
Expected output
['Mia', 'Leo', 'Ada']
['Sam', 'Kai']
['Mia', 'Leo', 'Ada', 'Sam', 'Kai']