all Python 3Loopsconstruct
for
for loop
A loop over the items of an iterable. It runs the loop body for every item: of a list, a string, a range, a dictionary and so on.
Syntax
for переменная in итерируемое:
блок
The loop variable does not vanish when the loop ends — it keeps its last value and stays visible in the surrounding code. The other common trap is mutating a list (adding or removing items) while iterating over it: the iteration goes wrong, so walk over a copy or build a new list instead.
Examples
for x in [1, 2, 3]:
print(x, end=" ") # → 1 2 3
for ch in "abc":
print(ch, end="") # → abc
for i in range(5):
print(i, end=" ") # → 0 1 2 3 4
d = {"a": 1, "b": 2}
for k, v in d.items():
print(f"{k}:{v}", end=" ") # → a:1 b:2
for i, val in enumerate(["x", "y", "z"], start=1):
print(f"{i}.{val}", end=" ") # → 1.x 2.y 3.z
for a, b in zip([1, 2], [10, 20]):
print(a + b, end=" ") # → 11 22
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy