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

23.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 23.1, “Python's block structure”.)

for V in S:

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

In general, you can use any number of induction variables. In this case, the members of the controlling iterable must themselves be iterables, which are unpacked into the induction variables in the same way as sequence unpacking as described in Section 22.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 {1} day of Hogswatch, my true love gave "
...             "to me".format(day) )
...     print "{0} {1}".format(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

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 iterable normally. Modifying the controlling iterable itself won't change anything; Python makes a copy of it 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