Custom Search

Tuesday, April 12, 2011

Python create Generator object using yield range xrange

Python create Generator object using yield range xrange

All python programmers are familiar with for-loops, and their ability to iterate over a list. What some programmers may not know, is that you can also use generator functions.

For instance, take the humble range function, which returns a list of incremental numbers. This is useful enough in some cases, but less useful when used in a for-loop that will run for thousands of iterations:

for i in range(10000):
# do something

This function is rather inefficient, as it generates a list of 10'000 numbers before it even begins the loop, using up a lot of memory and CPU time. So how can this be improved?

An easy way is to use a generator function and the yield keyword:
def quick_range(x):
i = 0
while i < x:
yield i
i += 1

for i in quick_range(10000):
# do something

Due to the yield keyword, quick_range returns a generator object when called. This generator object has a function called next() that returns i each time it is called. When the loop ends, a StopIteration exception is thrown.

This generator function can be used in for loops in much the same way as a list is. It's also faster, since there is no need to allocate memory for a 10'000 member list.

Because iterating over large numbers is a common problem, Python supplies the xrange function, which is similar in nature to the quick_range function, as supplied above. Using xrange when dealing with large numbers can dramatically increase the efficiency of your program.

No comments:

Post a Comment