next up previous contents
Next: for loops and the Up: Programming Previous: if statement   Contents


for loops

The for loop allows you to iterate over all the values in a sequence (string, list or tuple), performing the same task on each of the elements. In addition, starting with version 2.0, it's possible to iterate over other objects, such as file objects or dictionaries. The basic form of the for loop is:
              for var in sequence:
                  statements
              else:
                  statements
As with the if statement, there must be a colon at the very end of the for statement. The variable var is a ``dummy'' variable; its value is defined locally with the for loop, but when the for loop is completed, it will be equal to the last element in the sequence being processed.

Unlike the for statement, where the else (or elif) clause is often used, the optional else clause of the for loop is rarely used. The statements following the else statement are executed when the complete sequence of iterations defined by the for loop is completed. If a break statement (Section 6.8) is encountered inside the for loop, however, these statements are not carried out, and control goes to the next executable statement after the body of the for/else loop.

If the elements of the sequence being iterated over contain tuples or lists of a common size, you can replace var with a comma separated list representing the unpacking of each individual element of sequence. While this doesn't really provide any new capabilities to the for loop, it does add a certain amount of convenience when processing sequences of this sort.

Suppose we have a sequence of tuples containing the last name and first names of people, and we wish to print the first names followed by the last names. Since the for loop lets us iterate over the elements of a sequence, and, in this case, the sequence consists of tuples of length two, we could access the names as follows:

>>> names = [('Smith','John'),('Jones','Fred'),('Williams','Sue')]
>>> for i in names:
...     print '%s %s' % (i[1],i[0])
...
John Smith
Fred Jones
Sue Williams
By using the tuple unpacking feature of the for loop, we can express the same idea in an easier to understand form:
>>> for last,first in names:
...     print '%s %s' % (first,last)
...
John Smith
Fred Jones
Sue Williams

As an example of iterating over a non-sequence, consider the file object introduced in Section 5.4. Once you've created a file object suitable for reading, iterating over the object will advance to the next line in the file. So to find the longest line in a file, you could use a for loop like the following:

try:
	f = open('some.file','r')
except IOError:
	print >>sys.stderr, "Couldn't open %s" % 'some.file'
	sys.exit(1)

maxlen = 0
for line in f:
	l = len(line)
	if l > maxlen:
		maxlen = l

print 'Maximum length = %d' % maxlen


next up previous contents
Next: for loops and the Up: Programming Previous: if statement   Contents
Phil Spector 2003-11-12