typestar

List comprehensions in Python

Building a list from a loop in a single expression.

numbers = range(1, 21)

squares = [n * n for n in numbers]
evens = [n for n in numbers if n % 2 == 0]
labels = [f"#{n:02d}" for n in evens]

words = ["kea", "owl", "albatross", "tui"]
long_words = [w.upper() for w in words if len(w) > 3]

pairs = [(w, len(w)) for w in words]

How it works

  1. [n * n for n in numbers] maps every item.
  2. An if clause at the end filters items out.
  3. The body can be any expression, like an f-string.

Keywords and builtins used here

The run, in numbers

Lines
10
Characters to type
275
Tokens
106
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 67 seconds.

Type this snippet

Step 1 of 4 in Comprehensions, step 1 of 53 in Pythonic Python.

Next →