What are comprehensions?

Comprehensions offer an easy and compact way of creating lists, sets, and dictionaries.

A comprehension works by looping or iterating over items and assigning them to a container like a list, set, or dictionary.

This container cannot be a tuple because a tuple is unable to receive assignments due to its immutability.

List comprehension

List comprehension consists of square brackets containing an expression, followed by a for clause, and zero or more for or if clauses.

The general form of a list comprehension is:

lst = [expression for var in sequence [optional for and/or if]]

Simple examples

Examples of list comprehension are shown below:

Get hands-on with 1400+ tech skills courses.