CHAPTER 9 · 5 lessons · 65 exercises

Comprehensions

Build a new list out of an old one in a single line. Nothing else feels quite as much like Python.

0 / 65 solved

"I want a new list with everything in this one doubled." You write something like that daily. With what you learned in Chapter 2 you make an empty list, loop with for, and add with append — three or four lines.

Python has a way of writing that in one line made for exactly this. It is called a comprehension.

Write [x * 2 for x in numbers] and you have your new list. Read it as "for each x in numbers, a list of x * 2". The order feels backwards until you are used to it, and then it reads better than the long form, because what you are making is right there at the front of the line.

You can add an if as well. [x for x in numbers if x > 0] gives you "a list of only the ones above zero". Transforming and filtering, in one line.

Why give this a whole chapter? Because you cannot get through reading Python without it. Open any Python on GitHub and comprehensions are there. Not being able to write one costs you nothing; not being able to read one stops you dead. So the goal here is less "you can write them" and more "you know what it means the moment you see it".

Later in the chapter come nested ones (unpacking a list of lists in one go) and the same idea applied beyond lists. Swap the brackets for braces and you get a dictionary ({k: v for ...}); leave just the values and you get a set. The skeleton is identical; only the surrounding punctuation changes.

One caution to go with it. A comprehension is short, but pack too much in and nobody can read it. Three levels of nesting with two ifs is kinder written out as an ordinary for. Shortness is not the goal. Readability is the goal, and most of the time a comprehension serves it — please keep them in that order.

Lessons in this chapter

Build it all in one line

  1. 84Building a list in one line[x * 2 for x in numbers]. The three lines of make, loop and add come down to one.Go to the exercises
  2. 85Keeping only the ones you wantAn if at the back filters; an if at the front switches between two. The position changes the meaning.Go to the exercises
  3. 86Unpicking a nested listTwo fors side by side flatten a list of lists in one go. Write them outermost first.Go to the exercises
  4. 87Dictionaries in one line tooChange the brackets for braces and write key: value, and what you get is a dictionary. The skeleton is the same.Go to the exercises
  5. 88The container that drops duplicatesBraces with no colon give you a set. Anything that turns up twice is folded into one.Go to the exercises

Next up is “Higher-order functions and lambdas”. Pass a function as a value. Once the work itself can be an argument, what you are able to write changes.