The object returned by range() (or xrange() in Python2.x) is called generator .
Instead of storing the entire range [0,1,2,..,9] in memory, the generator stores the definition for (i=0; i<10; i+=1) and calculates the next value only when necessary (AKA lazy-evaluation )
Essentially, a generator allows you to return a list as a structure, but here are some differences:
- The list saves all items when it is created. The generator generates the next element when necessary.
- The list can be repeated as necessary, the generator can be repeated only once.
- A list can receive elements by index, a generator cannot - it only generates values once, from beginning to end.
A generator can be created in two ways:
(1) Very similar to a list comprehension:
# this is a list, create all 5000000 x/2 values immediately, uses [] lis = [x/2 for x in range(5000000)]
(2) As a function, using yield to return the following value:
Note: Even if range(5000000) is a generator in Python3.x, [x/2 for x in range(5000000)] is still a list. range(...) does the job and generates x one at a time, but the entire list of x/2 values will be computed when this list is created.
bcorso Dec 12 '13 at 4:58 2013-12-12 04:58
source share