A list is almost the opposite of lazy. The best example would be the difference between range
and xrange
; range
creates a list, while xrange
lazily gives you each number as you need it, using a generator.
>>> total = 0
>>> for i in range(2**30):
total += i
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
for i in range(2**30):
MemoryError
>>> print total
0
>>> for i in xrange(2**30):
total += i
>>> print total
576460751766552576
Many of the places that will take a list will also take a generator in its place. This is so true that Python 3 does away with xrange
entirely, and uses it to replace the normal range
.
>>> total2 = sum(xrange(2**30))
>>> print total2
576460751766552576
It's easy to make your own generator:
>>> def myrange(n):
i = 0
while i < n:
yield i
i += 1
>>> sum(xrange(10))
45
>>> sum(myrange(10))
45
>>> myrange(10)
<generator object myrange at 0x02A2DDA0>
And if you do really need a list, that's easy too. But then of course it's no longer lazy.
>>> list(myrange(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]