15

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.

3
  • 1
    See here: Know when to be Lazy. In short: either use generator expressions or use the itertools module. Commented Mar 8, 2013 at 1:24
  • @RobertHarvey: Nice link. In fact, other than doing x*2 instead of x**2, the blog is pretty much perfectly tailored to this question! Commented Mar 8, 2013 at 1:27
  • @RobertHarvey Very nice article. Thank you! Commented Mar 8, 2013 at 1:32

2 Answers 2

43

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())
Sign up to request clarification or add additional context in comments.

2 Comments

+1 for recommending the generator expression. Wherever you need lambda, map() isn't a good choice.
Thanks for your reply. I just tried to make a simpler code sample for the question (when using map).
4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.