substituting list comprehensions for map()

J Kenneth King james at agentultra.com
Mon Nov 2 14:45:28 CET 2009


Steven D'Aprano <steven at REMOVE.THIS.cybersource.com.au> writes:

> On Sun, 01 Nov 2009 23:54:16 -0800, Jon P. wrote:
>
>> I'd like to do:
>> 
>> resultlist = operandlist1 + operandlist2
>> 
>> where for example
>> 
>> operandlist1=[1,2,3,4,5]
>> operandlist2=[5,4,3,2,1]
>> 
>> and resultlist will become [6,6,6,6,6].  Using map(), I can do:
>> 
>> map(lambda op1,op2: op1 + op2, operandlist1, operandlist2)
>
>
> If the two lists are very large, it would be faster to use this:
>
>
> from operator import add
> map(add, operandlist1, operandlist2)

This is the best solution so far.

>
>
>> Is there any reasonable way to do this via a list comprehension ?
>
> [x+y for (x, y) in zip(operandlist1, operandlist2)]
>
> If the lists are huge, you can save some temporary memory by replacing 
> zip with itertools.izip.

I understand the OP was asking for it, but list comprehensions aren't
the best solution in this case... it would just be line noise.

List comprehensions are good for one-off transformations where it would
only create a one-time method for map to use.



More information about the Python-list mailing list