Comprehensions

INPUT · Slides

Building a list in one line

01 / 07

The three lines you always write

"I want a new list with everything in this one doubled." Work of that shape comes up constantly.

The way you have it now takes three steps. Make an empty list, loop with for, add with append.

numbers = [1, 2, 3]doubles = []for x in numbers:    doubles.append(x * 2)print(doubles)

Result

[2, 4, 6]

02 / 07

The same thing in one line

Python has a way of writing made for this shape alone. It is called a comprehension.

Inside the square brackets you write what you are making for a name in what you are looping over. That on its own gives you the new list.

numbers = [1, 2, 3]doubles = [x * 2 for x in numbers]print(doubles)

Result

[2, 4, 6]

03 / 07

Side by side

Put the two next to each other. The result is exactly the same.

doubles = []for x in numbers:    doubles.append(x * 2)
doubles = [x * 2 for x in numbers]

Four lines down to one. And you cannot forget to set up the empty list, because there is no longer an empty list to forget.

numbers = [1, 2, 3]a = []for x in numbers:    a.append(x * 2)b = [x * 2 for x in numbers]print(a)print(b)print(a == b)

Result

[2, 4, 6]
[2, 4, 6]
True

04 / 07

The order you read it in

Read [x * 2 for x in numbers] like this.

**"For each x in numbers, a list of x * 2."**

Until you are used to it the order feels backwards. Read the for x in numbers at the end first, then come back to the x * 2 at the front.

Once you are used to it, though, this is the easier one to read, because what you are making sits at the front of the line. In the for version you have to reach the append on the fourth line before you know what is being built.

names = ["Yui", "Haruto"]print(["Hi, " + n for n in names])

Result

['Hi, Yui', 'Hi, Haruto']

05 / 07

Anything you can loop over will do

What follows in does not have to be a list. Anything you can loop over with for can go there — a range, a string, whatever you like.

The "things you can loop over" from Chapter 8 pay off directly here.

print([x * x for x in range(1, 6)])print([c for c in "abc"])

Result

[1, 4, 9, 16, 25]
['a', 'b', 'c']

06 / 07

Why bother learning this

Honestly, you can get by without ever writing one. for and append will do everything a comprehension does.

The reason it gets a whole chapter anyway is that not being able to read one stops you dead. Open any Python on GitHub and comprehensions are there. They are in the code you are handed at work and inside every library you use.

So the goal here is less "you can write them" and more you know what it means the moment you see it.

07 / 07

Shortness is not the goal

One thing to watch: writing it short is not the point in itself.

The point is readability, and most of the time a comprehension serves it — please keep them in that order. Pack so much in that nobody can read it and you have lost what you came for.

Next lesson we add an if and learn how to keep only the ones you want.