Name

The for Statement

Synopsis

for target in sequence: 
    suite
[else:
    suite]

Sequence iteration. Assigns items in sequence to target and runs first suite for each. Runs else suite if loop exits without hitting a break statement. target may be anything that can appear on the left side of an “=” assignment statement (e.g., for (x, y) in tuplelist:).

In 2.2, works by first trying to obtain an iterator object with iter(sequence) and then calling that object’s next( ) method repeatedly until StopIteration is raised (see The yield Statement). In earlier versions, or if no iterator object can be obtained (e.g., no _ _iter_ _ method is defined), works instead by repeatedly indexing sequence at successively higher offsets until an IndexError is raised.

Get Python Pocket Reference, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.