Lesson 10 of 14 · 9 min

Comprehensions

A loop that builds a list is so common that Python has a shortcut for it: a list comprehension.

# with a loop
doubled = []
for n in [1, 2, 3]:
    doubled.append(n * 2)

# the same, as a comprehension
doubled = [n * 2 for n in [1, 2, 3]]   # [2, 4, 6]

Read it as: "a list of n * 2, for each n in the list".

Filtering

Add if at the end to keep only some items:

evens = [n for n in range(10) if n % 2 == 0]   # [0, 2, 4, 6, 8]

Dictionary comprehensions

The same idea with curly braces and key: value builds a dictionary:

prices = {"bread": 1.5, "milk": 1.2}
with_tax = {item: round(p * 1.15, 2) for item, p in prices.items()}
# {"bread": 1.73, "milk": 1.38}

Use comprehensions when the logic fits comfortably on one line. If you need several steps, a normal loop is clearer.

Your task

Write each function as a single comprehension:

  1. squares(n): the squares of 1 up to and including n.
  2. long_words(words): the words longer than 4 letters, in upper case.
  3. name_lengths(names): a dictionary from each name to its length.
main.py
def squares(n):
    pass


def long_words(words):
    pass


def name_lengths(names):
    pass


print(squares(6))
print(long_words(["cow", "goat", "chicken", "donkey"]))
print(name_lengths(["Farai", "Jo"]))

Python 3.14 runs right here in your browser. The first run downloads about 10 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…