The for Statement

for target in iterable:

suite [else: suite]

The for loop is a sequence (or other iterable) iteration that assigns items in iterable to target and runs the first suite for each. The for statement runs the else suite if the loop exits without hitting a break statement. target can be anything that can appear on the left side of an = assignment statement (e.g., for (x, y) in tuplelist:).

Since Python 2.2, this works by first trying to obtain an iterator object I with iter(iterable) and then calling that object's

I._next_() method repeatedly until Stoplteration is raised

(I.__next_() is named in Python 2); see "The yield

Statement" on page 68 for more on iteration. In earlier versions, or if no iterator object can be obtained (e.g., no __iter__ method is defined), this works instead by repeatedly indexing iterable at successively higher offsets until an IndexError is raised.

Was this article helpful?

0 0

Post a comment