Back
+10 XP
Concept

List Comprehensions: Replacing Messy Loops

List comprehensions create new lists in a concise one-line syntax: `[expression for item in iterable]`.

python
nums = [1, 2, 3, 4]
squares = [n * n for n in nums]
print(squares)  # [1, 4, 9, 16]

# 99. List Comprehensions: Replacing Messy Loops List comprehensions create new lists in a concise one-line syntax: `[expression for item in iterable]`: ```python nums = [1, 2, 3, 4] squares = [n * n for n in nums] print(squares) # [1, 4, 9, 16] ``` Instead of initializing an empty list `out = []`, looping over items with `for`, and calling `.append()`, list comprehensions do everything in one expressive, optimized C-level loop.

Checkpoint

What does `[x * 2 for x in [10, 20]]` produce?

Practice

Given `words = ["cat", "dog"]`, use a list comprehension to produce a list with each word capitalized using `.upper()`. Print the result.

Terminal
01
Tap code blocks below to assemble
Available Blocks