Python Glossary Русский

all Python 3Loopsconstruct

Nested loops

nesting

A loop inside another loop. The inner loop runs in full on every iteration of the outer one. break/continue affect only the nearest loop.

Syntax

for i in ...:
    for j in ...:
        блок

Mind the complexity: nesting multiplies the lengths, so two loops over n items are already O(n²), which becomes a bottleneck fast. Python has no labelled break, so you can't jump out of every level at once — use a flag, or move the loops into a function and return.

Examples

for i in range(1, 4):
    for j in range(1, 4):
        print(f"{i}*{j}={i*j}", end="  ")
    print()  # таблица умножения 3x3
matrix = [[1, 2, 3], [4, 5, 6]]
for row in matrix:
    for val in row:
        print(val, end=" ")  # → 1 2 3 4 5 6
found = False
for i in range(3):
    for j in range(3):
        if i == 1 and j == 1:
            found = True
            break
    if found:
        break
print(found)  # → True
pairs = [(i, j) for i in range(3) for j in range(3) if i != j]
print(len(pairs))  # → 6

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy