substituting list comprehensions for map()

Ben Finney ben+python at benfinney.id.au
Mon Nov 2 09:19:41 CET 2009


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

> I'd like to do:
>
> resultlist = operandlist1 + operandlist2

That's an unfortunate way of expressing it; it's valid Python syntax
that doesn't do what you're describing (in this case, it will bind
‘resultlist’ to a new list that is the *concatenation* of the two
original lists).

> map(lambda op1,op2: op1 + op2, operandlist1, operandlist2)
>
> Is there any reasonable way to do this via a list comprehension ?

Yes, just about any ‘map()’ operation has a corresponding list
comprehension. (Does anyone know of a counter-example, a ‘map()’
operation that doesn't have a correspondingly simple list
comprehension?)

For the above case, this is how it's done::

    >>> operandlist1 = [1, 2, 3, 4, 5]
    >>> operandlist2 = [5, 4, 3, 2, 1]
    >>> resultlist = [(a + b) for (a, b) in zip(operandlist1, operandlist2)]
    >>> resultlist
    [6, 6, 6, 6, 6]

-- 
 \     “Creativity can be a social contribution, but only in so far as |
  `\            society is free to use the results.” —Richard Stallman |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list