Python Glossary Русский

all Python 3astterm

ast.ListComp

expressions

The node for a list comprehension [elt for … in … if …]: elt is the element expression, generators is a list of comprehension nodes.

Syntax

ast.ListComp(elt, generators)

Nested for clauses go into generators in the order written, outermost first: [y for x in m for y in x] gives two comprehension nodes, the second iterating over the first's target. A conditional in elt ('a if c else b for …') is an IfExp inside elt, not a filter: only an if after for is a filter, and it lands in ifs. The loop target is a Name with ctx=Store.

Examples

import ast
lc = ast.parse('[y for x in m for y in x if y]', mode='eval').body
print(type(lc).__name__, len(lc.generators))  # → ListComp 2
print([g.target.id for g in lc.generators], len(lc.generators[1].ifs))  # → ['x', 'y'] 1
import ast
lc = ast.parse('[a if c else b for a in s]', mode='eval').body
print(type(lc.elt).__name__, lc.generators[0].ifs)  # → IfExp []

See also

Open in the full glossarydocs.python.orgReport an inaccuracy