for Loops

The for loop is a generic sequence iterator in Python: it can step through the items in any object that responds to the sequence indexing operation. The for works on strings, lists, tuples, and new objects we’ll create later with classes. We’ve already seen the for in action, when we mentioned the iteration operation for sequence types in Chapter 2. Here, we’ll fill in the details we skipped earlier.

General Format

The Python for loop begins with a header line that specifies an assignment target (or targets), along with an object you want to step through. The header is followed by a block of indented statements, which you want to repeat:

for <target> in <object>:   # assign object items to target
    <statements>            # repeated loop body: use target
else:
    <statements>            # if we didn't hit a 'break'

When Python runs a for loop, it assigns items in the sequence object to the target, one by one, and executes the loop body for each.[24] The loop body typically uses the assignment target to refer to the current item in the sequence, as though it were a cursor stepping through the sequence. Technically, the for works by repeatedly indexing the sequence object on successively higher indexes (starting at zero), until an index out-of-bounds exception is raised. Because for loops automatically manage sequence indexing behind the scenes, they replace most of the counter style loops you may be used to coding in languages like C.

The for also supports an optional else block, which works exactly ...

Get Learning Python 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.