QuickRange
We are all familiar with Python’s built-in range() function. Many of us use it all the time, especially in for loops, and especially if you come from a language that uses the
1 | for (i=0;i<j;i++){} |
syntax, but few of us realize just how inefficient range() is until we try to use it with really large numbers. When you call range(x), the interpreter is actually creating a list of numbers from 0 to x-1. That’s fine for range(10), but what if you have to go to range(1000000000000000)? Go try it, let me know how long it takes to start running your loop. A better solution is to use a generator, as follows:
1 2 3 4 5 6 7 8 9 | def quickrange(x): i=0 while i<x: yield i i+=1 for i in quickrange(10): print i #will print 0-9 |
The benefit of using a generator is that you don’t need to store an arbitrarily long list in memory (which can take up quite a lot of memory if your range is large enough). You also don’t have the delay in starting your loop while Python makes a list of x elements. The sample above is quite simple, of course, and doesn’t fully replicate the abilities of range(), but one could easily add some logic to handle start and (potentially negative) step values.