A shop converts prices from whole units to display strings.
What You Need to Understand
A list comprehension creates a list by evaluating an expression for each item in an iterable. It can express a simple transformation in one readable statement.
When to Use It
A shop converts prices from whole units to display strings.
Step-by-Step Python Example
prices = [5, 10, 15]
doubled_prices = [price * 2 for price in prices]
print(doubled_prices)
How the Example Works
For each price, the expression price * 2 is evaluated and collected in order. The original list remains unchanged.
Example Output
[10, 20, 30]
['Maya', 'Dan']
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
names = ["maya", "dan"]
print([name.title() for name in names])
Important Behavior and Edge Cases
A comprehension should be easy to read. Use an explicit loop when logic involves several actions or side effects.
Try It Yourself
Produce a list containing squares of the integers from 1 through 5.
Common Beginner Mistakes
- A comprehension should be easy to read. Use an explicit loop when logic involves several actions or side effects.
- Assuming every sequence operation modifies the original data or that a tuple makes nested mutable objects immutable.
Key Takeaways
- A list comprehension creates a list by evaluating an expression for each item in an iterable.
- For each price, the expression
price * 2is evaluated and collected in order. - A comprehension should be easy to read.