Comprehensions in Python
Chapter 12: Comprehensions
4 short lessons, with 3D animations, quizzes and coding tasks.
The lessons
List comprehensions
[expression for name in source] builds a new list with one item, the expression, for each item of the source.
Filtering with if
[expression for name in source if condition] keeps only the items whose condition is True, then makes the expression from each one.
Set and dictionary comprehensions
With curly braces, a comprehension builds a set ({expression for ...}) or, with key: value at the front, a dictionary ({key: value for ...}).
Comprehensions inside comprehensions
Two for parts in one comprehension run like nested loops, the first one outside, and a comprehension inside another builds a list of lists.