Start learning free

LESSON 114 OF 673 · LISTS I

Slicing a List in Python

Lesson

TL ; DR:

my_list[i:j] is a new list with the items from index i up to, not including, j. The original list doesn't change.


letters = ["a", "b", "c", "d", "e"]

middle = letters[1:4]
print(middle)    # ['b', 'c', 'd']

print(letters)   # ['a', 'b', 'c', 'd', 'e']


Full lesson:

Sometimes you need only part of a list, like the first few items. Slicing copies that part into a new list.

Write the start index and the end index in brackets, with a colon between them. The item at the end index is not included. So letters[1:4] has the items at 1, 2 and 3.

That makes the length easy to see: 4 - 1 = 3 items.

Leave out the start to begin at index 0. Leave out the end to go to the very end:

print(letters[:2])   # ['a', 'b']
print(letters[3:])   # ['d', 'e']

Negative indexes work too. So letters[-2:] is the last two items, ['d', 'e'].

The original list stays as it was. Changing the new list doesn't change it either.

A slice never fails on a big index. So letters[3:100] is simply ['d', 'e'].


Your task

runners holds a race's runners, in the order they finished.

Put the first three in a new list named podium. Put everyone else, from index 3 to the end, in one named rest.

The code below prints both, then the length of runners.

Expected output:

Ana Ben Cleo
Dan Eve
5
STEP 1 OF 2
    Ctrl + Enter to check