Search code examples
pythonpython-2.7python-itertools

Map on iterators of different length


I was answering this question and faced the following problem:

>>> from operator import add
>>> map(add,[1,2,3],[1,2])

Traceback (most recent call last):
  File "<pyshell#47>", line 1, in <module>
    map(add,[1,2,3],[1,2])
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'

I wanted map to stop as soon as the smallest iterator provided in the parameters is consumed.

I found the solution:

>>> from itertools import imap
>>> list(imap(add,[1,2,3],[1,2]))
[2, 4]

But, why is that? Shouldn't their behavior be consistent?

Is it the best way I workaround the problem?


Solution

  • As described on the itertools.imap description:

    Make an iterator that computes the function using arguments from each of the iterables. If function is set to None, then imap() returns the arguments as a tuple. Like map() but stops when the shortest iterable is exhausted instead of filling in None for shorter iterables. The reason for the difference is that infinite iterator arguments are typically an error for map() (because the output is fully evaluated) but represent a common and useful way of supplying arguments to imap().