Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Statements and Keywords

The for statement

Reference for Python's for statement: iterate over any iterable, unpack items, use range, enumerate and zip, loop else, and avoid modifying a list while looping.

A for loop runs its body once for every item produced by an iterable: a list, tuple, string, dictionary, set, range, file, generator or any object that supports iteration. Python gets an iterator from the object with iter() and calls next() until StopIteration ends the loop.

There is no counter to manage and no condition to write. If you need positions, use enumerate(); to walk several sequences together, use zip().

Python
for letter in "abc":
    print(letter)

Try it

Python Looping over things

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Loop variable, else and mutation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
for target in iterable:
    body
else:
    after_loop_without_break
Part Description
target A name or a tuple/list pattern. Unpacking works: for k, v in pairs, for first, *rest in rows.
iterable Any object that iter() accepts. Evaluated once, before the loop starts.
else Optional. Runs once if the loop ends without hitting break.

Raises: TypeError if the object is not iterable; ValueError if unpacking a target fails. An exception in the body leaves the loop (the else is skipped).

Usage notes

  • Do not modify the collection you are iterating. Removing from a list skips elements; changing a dict's size raises RuntimeError. Loop over a copy (for x in items[:]), or build a new list with a comprehension.
  • The loop variable stays in scope after the loop (the last value, or unbound if the iterable was empty). Comprehensions, in contrast, do not leak their variable.
  • Prefer enumerate() to range(len(x)) and zip() to indexing two lists in parallel. zip stops at the shortest input unless you pass strict=True (3.10+).
  • Iterating a dictionary gives keys, in insertion order. Use .items() for pairs.
  • Iterators are consumed. A generator or file object can be looped only once.
  • Assigning to the loop variable does not change the sequence; for x in items: x = x * 2 leaves items as it was.
  • Late binding: lambdas or functions created in a loop see the variable's latest value unless you bind it with a default argument.
  • Infinite iterables such as itertools.count() need a break.
  • Performance: a comprehension or built-in (sum, map, any) is usually faster than an explicit loop that appends.