Course outline · 0% complete

0/27 lessons0%

Course overview →

List comprehensions

lesson 1-1 · ~12 min · 1/27

From loops to comprehensions

Transforming one list into another is the single most common move in working Python: pull one field out of every record, convert the units on every reading, normalize every string before saving it. Comprehensions are the tool Python added because that pattern shows up everywhere, and they are the first thing reviewers look for when judging whether Python code is fluent.

In Python for Beginners you built lists the long way: start with an empty list, loop, and append each item.

squares = []
for n in [1, 2, 3, 4]:
    squares.append(n * n)

That pattern is so common that Python has a one-line shortcut for it: the list comprehension. It builds a brand-new list from any sequence you can loop over.

squares = [n * n for n in [1, 2, 3, 4]]

Read it left to right as: build a list of `n n, for each n in this sequence*. Same result, one line, and no empty-list setup or append` call.

squares = []for n in nums:squares.append(n*n)[n*n for n in nums]three lines of loopone expression, gold part comes first
A list comprehension is the loop turned inside out: the value you would append moves to the front.

Code exercise · python

Run this program. Both versions build the exact same list, so the two printed lines match.

The expression can be anything

The part before for is a normal Python expression. It runs once per item, and its result lands in the new list. You can call functions, do string work, whatever you like:

names = ["ada", "linus", "grace"]
caps = [name.upper() for name in names]
# ["ADA", "LINUS", "GRACE"]

Two rules of thumb:

  • Use a comprehension when you are transforming every item of a sequence into a new list.
  • Keep using a plain for loop when the body has side effects (printing, saving files) or needs several statements.

Code exercise · python

Your turn. Use one list comprehension to build `lengths`, a list holding the length of each word (use `len(word)`). Then print it.

Code exercise · python

Your turn, one more rep. Convert each Celsius temperature to Fahrenheit with one comprehension using f = c × 9/5 + 32, and print the resulting list.

Quiz

What does [n + 1 for n in [10, 20, 30]] evaluate to?

Quiz

You need to print a message for every order while processing it. Comprehension or plain for loop?