Write Python list comprehensions for filtering, transforming and choosing a value per item.
A list comprehension builds a whole new list in a single expression. The full form is [expression for item in iterable if condition], and you read it from left to right as "take each item, test it, and work out a value for it".
numbers = [1, 2, 3, 4, 5, 6]
squares = [n * n for n in numbers]
print(squares) # [1, 4, 9, 16, 25, 36]
evens = [n for n in numbers if n % 2 == 0]
print(evens) # [2, 4, 6]
labels = ['even' if n % 2 == 0 else 'odd' for n in numbers]
print(labels) # ['odd', 'even', 'odd', 'even', 'odd', 'even']
Three different things are happening in that example. The first comprehension maps every item through an expression, so each number is squared and the result is a list of six values. The second one adds an if clause, which filters. The items that fail the test never appear in the output, which is why the result has four elements instead of six. The third one uses a conditional expression inside the comprehension, and that chooses a value for every single item without dropping any of them.
The difference between the if clause and the conditional expression is worth being able to explain, because the two look similar and they do completely different jobs. The if clause decides whether an item appears in the result at all. The conditional expression decides what value an item that is already included will hold. A comprehension is allowed to use both of them together.
There are two more details that trip people up. The expression comes first and the for clause comes after it, which is the opposite of the set notation that most people meet at school. And because the whole thing is one expression, a comprehension can be assigned to a variable, returned from a function, passed as an argument, or placed inside another comprehension.