Transform Lists with List Comprehensions
Core idea
A list comprehension builds a new list from an iterable (a value you can loop over). In [expression for item in iterable], Python visits each item in order, evaluates the expression for it and stores the result in the new list. Use this form when the transformation is short and clear.
boxes = [2, 4, 1]items = [n * 6 for n in boxes]print(items)Each box count becomes an item count; the order stays the same.
Compare with a loop
prices = [5, 8, 3]result = []for price in prices: result.append(price + 2)print(result)print([price + 2 for price in prices])Both approaches add the same fee to each price. The explicit loop is useful when more steps are needed.
Empty input and original list
values = [3, 5]print([n - 1 for n in values])print(values)print([n - 1 for n in []])This transformation does not change the original list. Empty input produces an empty list.
Common mistake
Do not put append() in the result expression to build another list: append changes a list and returns None. Use an ordinary loop for side effects such as printing.
Practice
Convert [3, 0, 7] from hours to minutes using a comprehension, then write the equivalent loop.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
List transformations
Check your understanding of list comprehensions.
What is printed?
print([n * 2 for n in [3, 1]])What is printed?
print([n + 1 for n in []])What is printed?
a = [3, 1]print([n + 1 for n in a])print(a)Which part calculates each output item in [n * 4 for n in values]?