Intermediate · 10 min
List comprehensions
Build transformed and filtered lists with a compact expression.
Transform a list
A list comprehension creates a new list by evaluating an expression for every item. Read it from left to right: result expression, loop, then the source collection.
prices = [3, 5, 8]
doubled = [price * 2 for price in prices]
print(doubled)Output
[6, 10, 16]
Filter while building
Add an if clause to keep only values that meet a condition. The original list is left unchanged.
scores = [48, 75, 62, 91]
passed = [score for score in scores if score >= 60]
print(passed)Output
[75, 62, 91]
List comprehensions
- Read both list comprehensions examples before answering.
- Run the task, compare its exact output, and revise the code if needed.
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Prepare a price list
Use a list comprehension to create discounted from prices by subtracting 2 from each price. Display the new list.
Put price - 2 before the for clause.