4.5.1 for loops

As mentioned in Section 3.6, Python's for loops are actually foreach loops: for each element in the list that follows, repeat the nested block that follows the for statement, e.g.

      >>> for i in 1,2,3,4:
              print i

                
      1
      2
      3
      4

This is fundamentally different to the way for loops work in other languages. It allows the index of the for loop (i in this example to step through arbitrary elements.

By using the range function we are replicating the behaviour of for loops in most other languages (C, Pascal, etc.). That is the index is implemented by a constant amount between an lower and upper bound.

However, in Python for loops are much more flexible. Consider the following example:

      >>> for i in 1,2,3,500:
              print i

                
      1
      2
      3
      500

This kind of thing is not easy to do in other languages.

The for loop usually steps through a list of items, but it can also be used with arrays:

      >>> from Numeric import *
      >>> xx = array([1,10.2,-509])
      >>> for i in xx:
              print i

              
      1.0
      10.2
      -509.0

This is very useful when writing functions which take array parameters whose size is not known in advance.