Map on iterators of various lengths

I answered this question and ran into 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 stop as soon as the smallest iterator contained in the parameters was consumed.

I found a solution:

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

But why? Should their behavior be consistent?

Is this the best way to solve the problem?

+3
source share
2 answers

As described in itertools.imap description:

Make an iterator that evaluates the function using the arguments from each of the repeating ones. If the function is set to No, then imap () returns the arguments as a tuple. Like map (), but it stops when the shortest iterable is exhausted, instead of filling None for shorter iterations. The reason for the difference is that infinite iterator arguments are usually an error for map () (since the output is fully computed), but they are a common and useful way to provide imap () arguments.

+4
source

How about: map(sum, zip([1,2,3],[4,5])) ?

+2
source

All Articles