Python 3D Academyবাংলা

Comprehensions in Python

Chapter 12: Comprehensions

4 short lessons, with 3D animations, quizzes and coding tasks.

The lessons

  1. List comprehensions

    [expression for name in source] builds a new list with one item, the expression, for each item of the source.

  2. 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.

  3. 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 ...}).

  4. 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.