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

2 quizzes

0/3 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".

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.

Quiz

What does this print?

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.