O'Reilly logo

Python: Essential Reference, Third Edition by David Beazley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Loops and Iteration

You implement loops using the for and while statements. For example:

while expression:
    statements
for i in s:
    statements

The while statement executes statements until the associated expression evaluates to false. The for statement iterates over all the elements of s until no more elements are available. The for statement works with any object that supports iteration. This obviously includes the built-in sequence types such as lists, tuples, and strings, but also any object that implements the iterator protocol.

An object, s, supports iteration if it can be used with the following code, which mirrors the implementation of the for statement:

 it = s.__iter__() # Get an iterator for s while 1: try: i = it.next() # Get next item ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required