for loop

Repeat code for each item of a sequence, such as a list, a string or a range.

Syntax

for item in sequence:
...
  • The loop variable takes each value in turn.

Example

for part in ["wrench", "cable"]:
    print(part.upper())

Output:

WRENCH
CABLE

Common mistakes

  • Changing a list while you loop over it gives surprising results. Loop over a copy instead.
  • The body must be indented.

Practise it