14. List comprehension

A list comprehension builds a new list in one line by applying an expression to every element of an iterable. Its form is:

  • expression — the value stored in the new list; it can use item.
  • item — the name for the current element, exactly as in a for loop.
  • iterable — the collection to walk through.

It is equivalent to creating an empty list and appending inside a for loop, but shorter. The result is always a new list.

Coming from JavaScript? A list comprehension is .map(): [n * 2 for n in numbers] is numbers.map(n => n * 2). The expression comes before the for.

#01

Double each number

Build a list comprehension that multiplies each number of [1, 2, 3] by 2, then print the new list.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#02

Uppercase each word

Use words = ["apple", "pear"]. Build a list comprehension with the uppercase version of each word, then print it.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#03

Collect the lengths

Use words = ["hi", "python", "code"]. Build a list comprehension with the length of each word, then print it.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#04

Build from a range

Build a list comprehension that adds 1 to each number of range(3), then print the new list.

Print exactly:

Create a free account to save your progress and unlock chapter 2.