Skip to content
CodeNest

Data StructuresLesson 12 of 1912 min

Comprehensions

Build a new list, set, or dict from an existing one in a single readable line.

By the end you will be able to

  • Rewrite a build-a-list loop as a list comprehension
  • Filter items with an if clause
  • Write dict comprehensions

The "make an empty list, loop, append" pattern is so common that Python has dedicated syntax for it: the comprehension.

Both blocks below produce the same result.

Python
Output
[1, 4, 9, 16, 25]
[1, 4, 9, 16, 25]
— expected output; press Run to execute it yourself

Read it as three parts, left to right after the brackets:

[ EXPRESSION for ITEM in COLLECTION if CONDITION ]

The optional if at the end filters — only items that pass reach the expression.

Python
Output
[2, 4, 6, 8, 10]
[4, 16, 36, 64, 100]
['Ada', 'Bob', 'Cleo']
['ada', 'cleo']
— expected output; press Run to execute it yourself
Python
Output
[3, 4, 9]
[3, 0, 4, 0, 9]
— expected output; press Run to execute it yourself

Set and dict comprehensions

Swap the brackets for braces to build a set, or add key: value to build a dict.

Python
Output
{3, 4, 5, 6}
{'apple': 5, 'fig': 3, 'banana': 6, 'kiwi': 4}
{'tea': 2.5, 'coffee': 3.8}
— expected output; press Run to execute it yourself

Exercise

Write long_words(words, n) returning a list of the words longer than n characters, all uppercased — using a single comprehension.

Python
Output

Press Run to execute this code.

Check your understanding

0/2 answered
  1. 1.What is [n * 2 for n in [1, 2, 3]]?
  2. 2.Which comprehension keeps only the strings longer than 3 characters?