livepython.net
CHAPTER 09Python Lists
9.3  SLICING

Python List Slicing: Get Part of a List

Slicing: Get Part of a List

Slicing takes a part of a list. Write list[start:stop], and Python gives you a new list with the items from start up to, but not including, stop.

Think of cutting a few slices from a loaf of bread. You choose where the knife starts and where it stops, and you take the piece in between.

PYTHONedit me
days = ["Mon", "Tue", "Wed", "Thu", "Fri"]
print(days[1:4])
OUTPUT
['Tue', 'Wed', 'Thu']
Item"Mon""Tue""Wed""Thu""Fri"
Index01234

days[1:4] starts at index 1 ("Tue") and stops before index 4, so "Fri" is left out.

The rules

  • start is included, stop is not.
  • The number of items you get is stop - start. Here, 4 - 1 = 3 items.
  • A slice is always a list, with brackets, even when it holds one item.

An item or a slice?

PYTHONedit me
days = ["Mon", "Tue", "Wed", "Thu", "Fri"]
print(days[2])
print(days[2:3])
print(days[0:2])
OUTPUT
Wed
['Wed']
['Mon', 'Tue']

days[2] with one number gives the item: the string Wed. days[2:3] with a colon gives a list that holds that item.

Common beginner doubt: why is stop left out?

It looks odd at first, but it makes slices fit together neatly. days[0:2] and days[2:5] share the number 2, and together they make the whole list, with no item twice and none missing. And stop - start is always the number of items.

list[start:stop] gives the items from start up to, but not including, stop.

your turnPredict the output

What will this print?

nums = [10, 20, 30, 40, 50] print(nums[1:3])
Your turn! What will this code show on the screen?

Slice from the Start or to the End

You can leave out the start or the stop of a slice. Leave out the start, and the slice begins at the front. Leave out the stop, and it runs to the end.

Think of a race result: "the first three" get medals, and "everyone from fourth place on" gets a certificate. You don't need to say where the list begins or ends.

PYTHONedit me
scores = [90, 85, 77, 64, 50]
print(scores[:3])
print(scores[3:])
OUTPUT
[90, 85, 77]
[64, 50]

The rules

SliceWhat you get
[:3]the first 3 items
[3:]everything from index 3 to the end
[-2:]the last 2 items
[:-1]everything except the last item
[:]the whole list (a copy, see lesson 4)

Negative numbers work in slices just like negative indexes:

PYTHONedit me
scores = [90, 85, 77, 64, 50]
print(scores[-2:])
print(scores[:-1])
OUTPUT
[64, 50]
[90, 85, 77, 64]

Slices never give an IndexError

A slice that goes past the end stops at the end. A slice with nothing in it gives an empty list:

PYTHONedit me
names = ["Sunny", "Rocky"]
print(names[:10])
print(names[5:])
OUTPUT
['Sunny', 'Rocky']
[]

Good: names[:3] for "the top three". If there are only two names, you get both, and no error.

Avoid: names[2] when the list might be short. An index past the end is an IndexError (topic 2).

Leave out start to begin at the front. Leave out stop to go to the end.

your turnFill the gap

Print the last two letters

letters = ["a", "b", "c", "d", "e"] print(letters[?])

It should print: ['d', 'e']

Which piece makes this code work?

Slice Step and Reversing a List

A slice can take a third number, the step: list[start:stop:step]. A step of 2 takes every second item. A step of -1 walks backwards, so list[::-1] gives the list in reverse order.

Think of climbing stairs two at a time. You still go from the bottom to the top, but you only step on every second stair.

PYTHONedit me
nums = [0, 1, 2, 3, 4, 5, 6, 7]
print(nums[::2])
print(nums[1::2])
print(nums[1:6:2])
OUTPUT
[0, 2, 4, 6]
[1, 3, 5, 7]
[1, 3, 5]

The rules

  • The step is how far to jump each time. When you leave it out, it's 1.
  • [::2] takes every second item, starting at the front.
  • [1::2] takes every second item, starting at index 1.
  • [::-1] takes every item, from the back to the front.

Reverse a list

PYTHONedit me
queue = ["Sunny", "Rocky", "Lucky"]
print(queue[::-1])
print(queue)
OUTPUT
['Lucky', 'Rocky', 'Sunny']
['Sunny', 'Rocky', 'Lucky']

[::-1] makes a new, reversed list. The original queue is unchanged, as the second line shows.

Avoid: a step of 0

A step of 0 would never move, so Python refuses it:

PYTHONedit me
nums = [1, 2, 3]
print(nums[::0])
OUTPUT
ValueError: slice step cannot be zero

Common beginner doubt: which number is which?

With two colons, the numbers are always start, stop, step, in that order. nums[1:6:2] means "start at 1, stop before 6, jump by 2". Empty places use the defaults: the front, the end, and a step of 1.

The third number is the step: [::2] takes every second item, and [::-1] reverses the list.

your turnPredict the output

What will this print?

nums = [1, 2, 3, 4, 5, 6] print(nums[::3])
Your turn! What will this code show on the screen?

A Slice Is a New List: Copy a List

Every slice is a new list. Changing the slice never changes the original. So the slice [:], with no numbers at all, is the easiest way to copy a list.

Think of a photocopy. Scribble on the copy as much as you like: the original page stays clean.

PYTHONedit me
original = [1, 2, 3]
copy = original[:]
copy[0] = 99
print(original)
print(copy)
OUTPUT
[1, 2, 3]
[99, 2, 3]

The surprise: = does not copy a list

PYTHONedit me
original = [1, 2, 3]
same = original
same[0] = 99
print(original)
OUTPUT
[99, 2, 3]

Wait, what? We changed same, and original changed too!

same = original doesn't make a second list. It puts a second name tag on the same list. Think of one box with two labels: whichever label you use, you open the same box.

Common beginner doubt: but chapter 4 said = copies!

In chapter 4, b = a and then a = 20 left b alone. That's still true here: a = 20 puts the label a on a new value. Here, though, same[0] = 99 doesn't move a label. It changes something inside the one list that both names share.

The rules

You writeWhat you get
backup = scores[:]a new list with the same items
backup = scoresthe same list with a second name
top = scores[:3]a new list; scores is unchanged

Slicing makes a new list, so list[:] is a copy. = only gives the same list a second name.

your turnPick the right idea

You want a backup of scores that stays the same when scores changes. Which line?

Think about it, then pick one.
your turnType the output

Type what this prints

x = input() print(x * 2)

The user types: 4

Read the code line by line, then type the output exactly.

Practice: Slicing

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 74.Python Program to Print the Top Three ScoresEasySolve
  2. 75.Python Program to Get the Last Few Temperatures from a ListMediumSolve