Home > Articles > Programming > Python

  • Print
  • + Share This
Like this article? We recommend

Loops

The simple loops shown earlier used the while statement. The other looping construct is the for statement, which iterates over 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]
d = range(8,1,-1)  # d = [8,7,6,5,4,3,2]

The for statement can iterate over any sequence type and isn't limited to sequences of integers:

a = "Hello World"
# Print out the characters in a
for c in a:
    print c

b = ["Dave","Mark","Ann","Phil"]
# Print out the members of a list
for name in b:
    print name

range() works by constructing a list and populating it with values according to the starting, ending, and stride values. For large ranges, this process is expensive in terms of both memory and runtime performance. To avoid this, you can use the xrange() function, as shown here:

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

a = xrange(100000000)    # a = [0,1,2, ..., 99999999]
b = xrange(0,100000000,5)  # b = [0,5,10, ...,99999995]

Rather than creating a sequence populated with values, the sequence returned by xrange() computes its values from the starting, ending, and stride values whenever it's accessed.

  • + Share This
  • 🔖 Save To Your Account