list comprehension

A compact Python expression that builds a new list by looping over items and optionally filtering them.

In more detail

It is written in square brackets, such as [x * 2 for x in numbers if x > 0], and reads as: the expression, for each item, optionally only if a condition holds. Braces give a set or, with key: value, a dictionary comprehension. When the logic needs several statements or side effects, a plain loop is clearer.

Examples

failed = [d for d in deploys if d["tag"] in remediations]
[w.upper() for w in words if len(w) > 3]

Related terms

Taught in

References

Certification courses