Search code examples
pythonlist-comprehensioniterable-unpackingmap-function

Map equivalent for list comprehension


[foo(item['fieldA'], item['fieldC']) for item in barlist]

Is there a map equivalent for this?

I mean, something like this:

map(foo, [(item['fieldA'], item['fieldB']) for item in barlist])

but it doesn't work. Just curious.


Solution

  • You are looking for itertools.starmap():

    from itertools import starmap
    
    starmap(foo, ((item['fieldA'], item['fieldB']) for item in barlist))
    

    starmap applies each item from the iterable as separate arguments to the callable. The nested generator expression could be replaced with an operator.itemgetter() object for more mapping goodness:

    from itertools import starmap
    from operator import itemgetter
    
    starmap(foo, map(itemgetter('fieldA', 'fieldB'), barlist))
    

    Like all callables in itertools, this produces an iterator, not a list. But if you were using Python 3, so does map(), anyway. If you are using Python 2, it may be an idea to swap out map() for itertools.imap() here.