GNU Info

Info Node: (python2.1-tut.info)for Statements

(python2.1-tut.info)for Statements


Next: range Function Prev: if Statements Up: More Control Flow Tools
Enter node , (file) or (file)node

`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 (e.g., a list
or a string), in the order that they appear in the sequence.  For
example (no pun intended):

     >>> # Measure some strings:
     ... a = ['cat', 'window', 'defenestrate']
     >>> for x in a:
     ...     print x, len(x)
     ...
     cat 3
     window 6
     defenestrate 12

It is not safe to modify the sequence being iterated over in the loop
(this can only happen for mutable sequence types, i.e., lists).  If you
need to modify the list you are iterating over, e.g., 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) > 6: a.insert(0, x)
     ...
     >>> a
     ['defenestrate', 'cat', 'window', 'defenestrate']


automatically generated by info2www version 1.2.2.9