List comprehensions
Not met yet
[price * 2 for price in prices] builds a new list by working something out for each item: a loop that collects, written in one line. Use one when you're building a list. When you're doing something for each item, like printing, use a plain for loop, because that's what a reader expects to find there.
Try it
main.pyOutput
Press Run and what your program prints shows up here.
Easy to get wrong
- Thinks a list comprehension leaves only the last value, as a loop variable does after a loop.
- Thinks the expression in a comprehension is applied to the whole list rather than to each item in turn.
- Thinks a comprehension is a good way to do something for each item, like printing, rather than to build a list.