Comprehensions with if
Not met yet
An if at the end of a comprehension keeps only the items that pass: [n for n in stock if n > 0]. An if ... else at the front keeps every item and chooses what to write for each: [n if n > 0 else "out" for n in stock]. Once you need two conditions, or an elif, write a plain loop; nobody can read the one-liner.
Try it
main.pyOutput
Press Run and what your program prints shows up here.
Easy to get wrong
- Thinks an if at the end of a comprehension changes values but keeps every item, rather than leaving some out.
- Thinks an if-else at the front of a comprehension leaves items out, rather than choosing a value for every item.
- Thinks an if without an else can go before the for to filter items.
- Thinks fewer lines always means clearer code, so any loop is better squeezed into one comprehension.