For loops in Python are quite versatile. The little keyword "in" allows you to loop through the elements of all kinds of sequences, may the elements be numbers, characters, strings, objects like tuples and more. Here is an example comparing range(), xrange() and a generator similar to xrange().
Experimenting with For Loops (Python)
# a short look at some for loops and range() functions
# for loops iterate through sequences with iter() and generator objects with iter().next()
# tested with Python24 vegaseat 18sep2005
# range( [start,] stop[, step] ) creates a list of needed integer numbers, okay for short lists
# test increment, step = 2
print range(0, 10, 2) # [0, 2, 4, 6, 8]
for k in range(0, 10, 2):
print k
print
# test decrement, step = -1, count down from 10 to 1
print range(10, 0, -1) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
for k in range(10, 0, -1):
print k
print
# xrange( [start,] stop[, step] ) function creates the integer number as needed, saves memory
#test
print xrange(0, 10, 2) # xrange(0, 10, 2)
print list(xrange(0, 10, 2)) # [0, 2, 4, 6, 8]
for k in xrange(0, 10,2 ):
print k
print
# qrange( [start,] stop[, step] ) is a generator, works similar to xrange()
def qrange(start, stop=None, step=1):
"""if start is missing it defaults to zero, somewhat tricky"""
if stop == None:
stop = start
start = 0
# allow for decrement
if step < 0:
while start > stop:
yield start # makes this a generator for new start value
start += step
else:
while start < stop:
yield start
start += step
# test
print qrange(0, 10, 2) # <generator object at 0x009D5E68>
print list(qrange(0, 10, 2)) # [0, 2, 4, 6, 8]
# for loop calls iter().next() to iterate through the generator object
for k in qrange(0, 10, 2): # could use just qrange(10, 2), since start defaults to 0
print k
print
# test decrement, count down from 10 to 1
for k in qrange(10, 0, -1):
print k
print
# qrange() also takes floating point numbers, range() and xrange() do not!
for k in qrange(0, 1.0, 0.2):
print k
print
# if you also want to show the index, use the new enumerate() function
for index, k in enumerate(range(0, 10, 2)):
print "%d: %d" % (index, k)
print
# similar using qrange()
for index, k in enumerate(qrange(0, 1.0, 0.2)):
print "%d: %0.1f" % (index, k)
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.