Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Comprehensions

Build a list, set or dictionary by nesting iteration clauses in written order and applying filters before the output expression.

Version: Python 3.14; repository image, production runtime not attested

Syntax

[f(x) for row in rows for x in row if keep(x)]

Build a list, set or dictionary by nesting iteration clauses in written order and applying filters before the output expression.

A comprehension’s iteration variables do not leak into the enclosing scope. A dictionary comprehension retains the last value for a repeated key without moving that key.

A generator expression defers producing results until consumed.

Examples

rows = [[2, 3], [4, 1]]
x = "outer"
print([x * 10 for row in rows for x in row if x % 2 == 0], x)
print({x % 2: x for row in rows for x in row})
source = iter([3, 4])
g = (n * 2 for n in source)
print(next(source), list(g))

Result

[20, 40] outer
{0: 4, 1: 1}
3 [8]

A generator expression defers producing results until consumed.

Sources