Keywords and Control Flow

for — Iterate over an iterable

Evaluate the iterable expression once, obtain an iterator, and bind the target to successive items. Targets may unpack items or use other assignment targets. The loop itself creates no new local scope; a name target retains its last assigned value if any iteration assigned it. An empty iterable does not assign that target. On exhaustion, an optional else runs unless control left the loop early via break, return or an uncaught exception. Async iteration uses a distinct async for statement.

Formal Syntax & Structure

python syntaxpython
for target in iterable:    suite[else:    suite]

Working Example

Example Snippetpython
prices = [("pen", 2), ("book", 7)]for name, price in prices:    print(name, price * 2)print(name)
Python Reference