substituting list comprehensions for map()

Ben Finney ben+python at benfinney.id.au
Tue Nov 3 00:01:00 EST 2009


Anh Hai Trinh <anh.hai.trinh at gmail.com> writes:

> > 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?)
>
> Try turning this into a list comprehension:
>
>   vectorsum = lambda *args: map(sum, zip(*args))

By “this” I take you to mean “the usage of ‘map’ in this code”, since
that's the limit of my question.

    >>> vectorsum = lambda *args: [sum(items) for items in zip(*args)]
    >>> vectorsum([1,2], [3,4], [5,6])
    [9, 12]
    >>> vectorsum([1,2], [3,4], [5,6], [7,8])
    [16, 20]

-- 
 \       “The apparent lesson of the Inquisition is that insistence on |
  `\         uniformity of belief is fatal to intellectual, moral, and |
_o__)    spiritual health.” —_The Uses Of The Past_, Herbert J. Muller |
Ben Finney



More information about the Python-list mailing list