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