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] ...

Get Python: Essential Reference, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.