list comprehension question

Terry Reedy tjreedy at udel.edu
Wed Oct 17 17:46:09 EDT 2012


On 10/17/2012 3:13 AM, rusi wrote:
> On Oct 17, 10:22 am, Terry Reedy <tjre... at udel.edu> wrote:
>> On 10/16/2012 9:54 PM, Kevin Anthony wrote:
>>
>>> I've been teaching myself list comprehension, and i've run across
>>> something i'm not able to convert.

My response is to the part Kevin could *not* convert, not the parts he 
did convert. I attempted to explain why he could not convert that part.

>> list comprehensions specifically abbreviate the code that they are
>> (essentially) equivalent to.
>>
>> res = []
>> for item in source:
>>     res.append(f(item))
>> res
>>
>> <==>
>>
>> [f(item) for item in source]
>>
>> Matrix multiplication does not fit the pattern above. The reduction is
>> number addition rather than list appending.
>
> Dunno why you say that.

Because it is true and because it makes an essential point about what 
one can and cannot sensibly do with comprehensions. They are not 
intended to be a replacement for *all* loops.

The essential inner reduction by addition of products that Kevin was 
'not able to convert' cannot be converted (with out some obnoxious 
trickery and *some* extra helper), so his request for a sensible 
conversion is futile.

> Heres matrix multiply using list comprehensions:

plus a helper function that does the inner reduction otherwise, as I 
implied it should be

> from operator import add
> def dot(p,q): return reduce(add, (x*y for x,y in zip(p,q)))

Right, this is the addition reduction that the OP was trying to
convert to a list comp. It cannot be done and you have not done it 
either. Note the the vector of products is produced as a comprehension. 
That you left it as a 'generator expression' is not relevant.

The important point is the the addition combines the products of 
different iterations and list comps, by their nature, cannot directly do 
that.

> def transpose(m): return zip(*m)
>
> def mm(a,b): return mmt(a, transpose(b))
>
> def mmt(a,b): return [[dot(ra, rb) for rb in b] for ra in a]

This is the repeated append part of the original nested loops and that, 
as I said, can be re-expressed as a list comp. But that was not the part 
Kevin was having difficulty with and not the part I was talking about.

-- 
Terry Jan Reedy




More information about the Python-list mailing list