Next / Previous / Contents / TCC Help System / NM Tech homepage

16.4. The for statement: Iteration over a sequence

Use a for statement to execute a block of statements repeatedly. Here is the general form. (For the definition of a block, see Section 16.1, “Python's block structure”.)

for V in S:
    B

The block is executed once for each value in S. During each execution of the block, V is set to the corresponding value of S in turn. Example:

>>> for color in ['black', 'blue', 'transparent']:
...     print color
... 
black
blue
transparent

In general, you can use any number of induction variables. In this case, the members of the controlling sequence must themselves be sequences, which are unpacked into the induction variables in the same way as sequence unpacking as described in Section 15.1, “The assignment statement: name = expression. Here is an example.

>>> fourDays = ( ('First', 1, 'orangutan librarian'),
...              ('Second', 5, 'loaves of dwarf bread'),
...              ('Third', 3, 'dried frog pills'),
...              ('Fourth', 2, 'sentient luggages') )
>>> for day, number, item in fourDays:
...     print ( "On the %s day of Hogswatch, my true love gave to me" %
...             day )
...     print ( "%d %s" % (number, item) )
... 
On the First day of Hogswatch, my true love gave to me
1 orangutan librarian
On the Second day of Hogswatch, my true love gave to me
5 loaves of dwarf bread
On the Third day of Hogswatch, my true love gave to me
3 dried frog pills
On the Fourth day of Hogswatch, my true love gave to me
2 sentient luggages

For those of you who like to break things, be advised that you can change the induction variable inside the loop, but during the next pass through the loop, it will be set to the next element of the controlling sequence normally. Modifying the control sequence itself won't change anything; Python makes a copy of the control sequence before starting the loop.

>>> for i in range(4):
...     print "Before:", i,
...     i += 1000
...     print "After:", i
... 
Before: 0 After: 1000
Before: 1 After: 1001
Before: 2 After: 1002
Before: 3 After: 1003
>>> L = [7, 6, 1912]
>>> for n in L:
...     L = [44, 55]
...     print n
... 
7
6
1912