functional programming with map()

Bengt Richter bokr at oz.net
Mon Feb 25 12:33:00 EST 2002


On 24 Feb 2002 21:59:51 -0800, Paul Rubin <phr-n2002a at nightsong.com> wrote:

>bokr at oz.net (Bengt Richter) writes:
>> but I didn't get an extra call trying your version:
>> 
>>  >>> reduce(lambda x,y:(y.f(),0)[1], items, 0)
>>  this is a
>>  this is b
>>  this is c
>>  0
>
>Didn't you?  'items' had three elements, but four values got printed.
True, but the zero was the interpretive loop printing the final value of
the reduce expression, which is not evidence of a y.f() call. All those
were logged by "this is ...".

My version of your reduce evaluated to None, so nothing extra printed,
but that was because the last y.f() call returned None, and the 'and 0'
actually didn't get a chance to do anything. I should have used
'y.f() and None or None' to guarantee a final None to prevent the
final interactive printout, if that was the goal.
>
>> you can use the 'and 0' ploy to get a zero length
>> list comprehension also:
>> 
>>  >>> [ 0 for x in items if x.f() and 0]
>>  this is a
>>  this is b
>>  this is c
>>  []
>
>Nice!  That's the best solutions so far.

Actually, I think I like

    reduce(lambda x,y: y.f(), items, 0)

best, since we're ignoring the final result anyway.

Regards,
Bengt Richter




More information about the Python-list mailing list