all Python 3astterm
ast.List
literals
The node for a list display [a, b, c]: elts holds the elements, ctx is Load when read or Store when the list is an assignment target.
Syntax
ast.List(elts, ctx)
The same syntax [a, b] yields a List with ctx=Store in '[a, b] = pair' and ctx=Load in 'print([a, b])' — an analyzer hunting for 'list creation' must look at ctx. A list comprehension is a different node, ListComp, and '[1] * 3' is a BinOp wrapping a List. A constant list is not folded into a Constant: [1, 2] stays a List of two Constant nodes.
Examples
import ast
node = ast.parse('[1, x]', mode='eval').body
print(type(node).__name__, [type(e).__name__ for e in node.elts]) # → List ['Constant', 'Name']
target = ast.parse('[a, b] = pair').body[0].targets[0]
print(type(target).__name__, type(target.ctx).__name__) # → List Store
See also
Open in the full glossarydocs.python.orgReport an inaccuracy