Search code examples
pythonpython-2.7collectionspython-itertools

Why does itertools.imap behave differently from map when None is passed as the mapping function?


imap(None, lst) seems to return the list with all items wrapped in 1-tuples, whereas map(None, lst) just returns (a copy of) the list:

>>> map(None, range(3))
[0, 1, 2]

>>> from itertools import imap
>>> list(imap(None, range(3)))
[(0,), (1,), (2,)]

Does anyone know the reason for this discrepancy? Is it intentional? Is it coincidental of some other design choices/factors? Is it a (design) defect? Does it serve a specific purpose that obviates itself in some particular combination of circumstances?


Solution

  • It is stated in itertools.imap documentation:

    ... 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().