substituting list comprehensions for map()

J Kenneth King james at
Tue Nov 3 16:22:28 CET 2009

Ben Finney <ben+python at> writes:

> J Kenneth King <james at> writes:
>> Steven D'Aprano <steven at> writes:
>> > from operator import add
>> > map(add, operandlist1, operandlist2)
>> This is the best solution so far.
> Strange to say it's a solution, when it doesn't solve the stated
> problem: to replace use of ‘map()’ with a list comprehension.

Granted I admit this later in my post.  It's not a solution to the OPs
request, but it is the best solution to such a case.

>> 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.
> I disagree; a list comprehension is often clearer than use of ‘map()’
> with a lambda form, and I find it to be so in this case.

The use of map expresses a value and implies the procedure by which it
is obtained.

The list comprehension expresses the procedure by which the value is

Both have uses and in some cases a list comprehension is definitely
preferrable to a map operation.

However in this case the procedure by which we derive the value is not
important or even interesting.  It is much more succinct to think of the
operation as a value and express it accordingly.  There's no need to
clutter the mind with extra name bindings and iteration keywords.  They
won't make our idea any more clear.

dot_product = map(mul, vec1, vec2)


dot_product = [a * b for a, b in zip(vec1, vec2)]

It's very clear, at least to me, what a dot-product is in this case.
Adding in the loop construct and name bindings doesn't enhance my
understanding of what a dot-product is.  I don't need to see the loop
construct at all in this case.  A dot product is simply the
multiplication of each element in a vector sequence.  It's more succinct
to simply think of the value rather then expressing the procedure to
construct that value.

This isn't a hammer issue.  Not every problem is a nail.

More information about the Python-list mailing list