Lesson 11: List comprehension
A list comprehension is a short way to build a new list from an existing sequence, in a single line. Instead of a loop with append, you write [expression for item in sequence]. You can also add an if condition to filter which items are included.
A list comprehension is an assembly line: each item goes in, gets a small transform, and comes out into a new list. An if condition is a quality check that lets only matching items through.
- list comprehension
- Building a new list in one line: [expression for item in sequence].
- expression
- What is computed for each item and placed into the new list (e.g. n*2).
- filter condition
- An if at the end of the comprehension that includes only items meeting the condition.