List comprehensions

Comprehensions & Iteration, lesson 1 of 5

⚡ Comprehensions & Iteration, lesson 1 of 5

List comprehensions

Transform and filter a list in a single readable line.

10 min

1 exercise

3 quizzes

0/4 solved

Getting Python ready… examples can run in a moment.

You've built many lists like this: start empty, loop, append. A list comprehension does it in one line:

[expression for item in iterable]

Read it as "expression for every item in iterable". The result is a brand new list.

Example

Loop vs comprehension

Both produce the same list. Try [p * 2 for p in prices].

Add an if at the end to keep only some items:

[x for x in items if condition]
Example

Filter and transform

Make a list of only the names that contain the letter "a".

Walkthrough

Filtering, one item at a time

temps182331271629250123456thot
Step 1 of 8

for t in temps starts with 18. The test 18 >= 25 is False, so nothing is added to hot.

checking now
kept
filtered out

hot = [t for t in temps if t >= 25]

Quiz

What does this print?

To choose between two values for every item, put an if … else expression at the front:

["pass" if s >= 50 else "fail" for s in scores]
Example

Pass or fail

Change the pass mark to 70.

Example

Flatten a grid

Two for clauses read left to right, like nested loops: for each row, for each number in it.

Walkthrough

Two for clauses = nested loops

grid[0]123012rowngrid[1]456012grid[2]789012flat10
Step 1 of 5

The outer loop sets row to grid[0]. The inner loop starts on that row: n is 1, so 1 goes into flat.

current row
just added
added earlier

flat = [n for row in grid for n in row]

Quiz

What does this print?

Older Python code often uses two built-in functions for the same jobs:

  • map(func, items): applies func to every item.
  • filter(func, items): keeps the items for which func(item) is True.

Both return a lazy iterator: values are produced only when you ask for them. print would show an object such as <map object ...>, so wrap the result in list().

Example

map and filter next to comprehensions

Each pair prints the same thing. Try print(map(len, words)) to see the lazy object that map gives back.

Quiz

What does this print?

Which should you use? Usually a comprehension, since it reads more clearly. map and filter are handy when a ready-made function does the job, like list(map(int, numbers)).

Exercise

Clean up the data

raw came from a messy form. Using comprehensions:

  1. clean: each entry stripped of spaces and in lower case, skipping entries that are blank.
  2. lengths: the length of each word in clean.