Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy map function in Python

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.

like image 355
Oscar Mederos Avatar asked Mar 08 '13 01:03

Oscar Mederos


2 Answers

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())
like image 148
JBernardo Avatar answered Sep 22 '22 12:09

JBernardo


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.
like image 28
Pavel Anossov Avatar answered Sep 25 '22 12:09

Pavel Anossov