O'Reilly logo

Python: Essential Reference, Third Edition by David Beazley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Iteration and Looping

The simple loop shown earlier used the while statement. The other looping construct is the for statement, which is used to iterate over a collection of items. Iteration is one of Python’s most rich features. However, the most common form of iteration is to simply loop over all the members of a sequence such as a string, list, or tuple. Here’s an example:

for i in range(1,10):
        print "2 to the %d power is %d" % (i, 2**i)

The range(i,j) function constructs a list of integers with values from i to j-1. If the starting value is omitted, it’s taken to be zero. An optional stride can also be given as a third argument. For example:

 a = range(5) # a = [0,1,2,3,4] b = range(1,8) # b = [1,2,3,4,5,6,7] c = range(0,14,3) # c = [0,3,6,9,12] ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required