Is there a way of making map
lazy? Or is there another implementation of it built-in in Python?
I want something like this to work:
from itertools import count
for x in map(lambda x: x**2, count()):
print x
Of course, the above code won't end, but I'd like just to enter any condition (or more complex logic) inside the for
and stop at some point.
use itertools.imap
on Python 2.x or upgrade to Python 3.x
You can also just use a simple generator expression that is far more pythonic:
foo = (x**2 for x in count())
itetools.imap
is lazy.
In [3]: itertools.imap?
Type: type
String Form:<type 'itertools.imap'>
Docstring:
imap(func, *iterables) --> imap object
Make an iterator that computes the function using arguments from
each of the iterables. Like map() except that it returns
an iterator instead of a list and that it stops when the shortest
iterable is exhausted instead of filling in None for shorter
iterables.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With