Home › Learn › Python › Lists

List comprehensions

Lesson 19 of 40. Build a list from another in one readable line.

A comprehension is a loop that builds a list, written inside the brackets: [x * x for x in nums] is the squares of the numbers. Add a condition at the end to keep only some items: [x for x in nums if x % 2 == 0]. It replaces the create-empty-list, loop, append pattern, and Python programmers use it constantly.

The expression before for can be anything: a calculation, a function call, a method call like word.upper(). Keep comprehensions short; when one needs a second line of thought, a plain loop is clearer.

words = ["hi", "hello", "hey"]
long_upper = [w.upper() for w in words if len(w) > 2]
print(long_upper)   # ['HELLO', 'HEY']

Your task

Using comprehensions, write squares(n) returning [1, 4, 9, ..., n*n], evens(nums) returning only the even numbers, and lengths(words) returning the length of each word.

Hint 1

[x * x for x in range(1, n + 1)]

Hint 2

[x for x in nums if x % 2 == 0]

Show the solution
def squares(n):
    return [x * x for x in range(1, n + 1)]


def evens(nums):
    return [x for x in nums if x % 2 == 0]


def lengths(words):
    return [len(w) for w in words]

    Runs CPython compiled to WebAssembly in this tab (12 MB download the first time, then cached); nothing is sent anywhere.