PythonLesson 12 of 16
List comprehensions in Python
A list comprehension is a short way to build a new list from an old one. What usually takes a loop and append fits on a single line.
Key points
- [expression for x in items] makes a list of transformed items
- [x for x in items if condition] keeps only the matching ones
- The original list stays untouched
- sum(), min(), max() and len() work nicely on the result
- If the line gets hard to read, go back to a normal loop
Example
squares = [n * n for n in range(1, 6)]print(squares) names = ["anna", "leo", "mia"]print([name.title() for name in names]) prices = [90, 450, 120, 700]cheap = [p for p in prices if p < 200]print(cheap)Three comprehensions: squares, names with a capital letter, and only the cheap prices. Each one replaces a three-line loop.
Task
How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.The weather log has five temperatures. Rewrite warm as a list comprehension that keeps only days of 20 degrees or more. The average works itself out.
Output
What your program prints appears here.