substituting list comprehensions for map()

Paul Rudin paul.nospam at rudin.co.uk
Mon Nov 2 09:17:59 CET 2009


"Jon P." <jbperez at gmail.com> writes:

> 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)
>
> Is there any reasonable way to do this via a list comprehension ?

You can do it as a list comprehension e.g. like this:

[ x + y for x, y in zip(operandlist1, operandlist2)]

Note that there is some unnecessary list building going on here and it
may be better to use itertools.izip. (In python 3 zip returns an
iterator anyhow.)



More information about the Python-list mailing list