← All lessons

List comprehension

Sign in · Sign up

Lesson 5.13

A list can be built in one line — that's a comprehension:

numbers = [1, 2, 3, 4]

squares = [x * x for x in numbers]          # the same as a loop with append
evens = [x for x in numbers if x % 2 == 0]  # with a condition

It reads like this: "collect x * x for each x in numbers". The order is exactly that: first what to collect, then for, then if.

The list of numbers numbers is set by the check. Print, in order:

  1. the list of numbers multiplied by factor;
  2. the list of only those numbers that are greater than limit.

Build both lists with a comprehension.

Hint

A comprehension is an expression in square brackets with a for inside.

[x * factor for x in numbers] gives a new list right away. Separate append calls and a loop are not needed, and the original list does not change.