# substituting list comprehensions for map()

J Kenneth King james at agentultra.com
Wed Nov 4 15:39:32 CET 2009

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

> On Tue, 03 Nov 2009 10:22:28 -0500, J Kenneth King wrote:
>
>> 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)
>>
>> vs
>>
>> 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.
>
> Except it's not.
>
> The dot product of two vectors returns a scalar, not another vector:
> http://en.wikipedia.org/wiki/Dot_product
>
> So what you want is:
>
> dot_product = sum(map(mul, vec1, vec2))

Derh. Thanks for the catch. My bad.

>> 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.
>
> What you need is to define a function dot-product, and not hijack the
> name for a local value. Then the function's implementation is irrelevant
> to you: it could use a list comp, or could use map, it could use a for-
> loop, a while loop, recursion, or black magic:
>
> scalar = dot_product(vec1, vec2)

Even better.

But now I'm afraid the example is running away from the point.

So to summarize:

1. Extra name bindings and loop keywords aren't always easier to read.

2. Expressing what we want rather than how we get it is much more clear.