Python Glossary Русский

all Python 3Lists (list)term

Nested list comprehension

comprehension

A list comprehension may contain several nested for clauses, which lets you build nested lists or flatten a matrix into a single list.

Syntax

[[выражение for j in inner] for i in outer]

Read the for clauses left to right exactly as nested loops top to bottom: the outer for row in matrix comes first, the inner for x in row second. Writing [x for x in row for row in matrix] is the classic mistake — row is not defined at that point, so you get a NameError. For transposing, zip(*matrix) is simpler, and past two levels of nesting a plain loop reads better than the comprehension.

Examples

matrix = [[1,2,3],[4,5,6],[7,8,9]]
flat = [x for row in matrix for x in row]
print(flat)   # → [1, 2, 3, 4, 5, 6, 7, 8, 9]
trans = [[row[i] for row in matrix] for i in range(3)]
print(trans)  # → [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
pairs = [(i,j) for i in range(3) for j in range(3) if i != j]
print(len(pairs))  # → 6
sq = [[i*j for j in range(1,4)] for i in range(1,4)]
print(sq[0])  # → [1, 2, 3]

See also

Open in the full glossarydocs.python.orgReport an inaccuracy