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”.)
forVinS:B
is a
variable called the induction
variable.
V
is any
expression that produces a value that is a sequence,
including iterators (see Section 17.2, “Iterators: Values that can produce a sequence of
values”) and generators (see Section 17.3, “Generators: Functions that can produce a sequence of
values”).
S
This sequence is called the controlling sequence of the loop.
is a
block of statements.
B
The block is executed once for each value in . During each
execution of the block, S is set to the corresponding
value of V in
turn. Example:
S
>>> 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: ”.
Here is an example.
name = expression
>>> 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