- publishing free software manuals
An Introduction to Python
by Guido van Rossum and Fred L. Drake, Jr.
Paperback (6"x9"), 124 pages
ISBN 0954161769
RRP £12.95 ($19.95)

Sales of this book support the Python Software Foundation! Get a printed copy>>>

4.2 for Statements

The for statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or giving the user the ability to define both the iteration step and halting condition (as C), Python's for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. For example (no pun intended):

    >>> # Measure some strings:
    ... a = ['egg', 'chips', 'spam']
    >>> for x in a:
    ...     print x, len(x)
    ... 
    egg 3
    chips 5
    spam 4

It is not safe to modify the sequence being iterated over in the loop (this can only happen for mutable sequence types, such as lists). If you need to modify the list you are iterating over (for example, to duplicate selected items) you must iterate over a copy. The slice notation makes this particularly convenient:

    >>> for x in a[:]: # make a slice copy of the entire list
    ...    if len(x) == 4: a.insert(0, x)
    ... 
    >>> a
    ['spam', 'egg', 'chips', 'spam']
ISBN 0954161769An Introduction to PythonSee the print edition