[Tutor] weird lambda expression -- can someone help me understand how this works

spir denis.spir at gmail.com
Sat Dec 14 15:28:16 CET 2013


On 12/14/2013 03:14 AM, Michael Crawford wrote:
> I found this piece of code on github
>      mkdict = lambda row: dict((col, row[col]) for col in cols)  #<<<<<<<<<<<<<<<<<<

Apart form the "lambda" part, explained by others, one point I would note that 
makes the whole expression weird and hard to decode is that it uses a mysterious 
'cols' coming from nowhere (technically, an unbound variable, also called 
"upvalue" in programming). This 'cols' is not even defined in the piece of code 
you posted (which is not all reproduced above).

Better would be, in my view, making it an explicit (bound) variable:
     mkdict = lambda (cols, row): dict((col, row[col]) for col in cols

Which is just a funny and obscure [*] way to say:
     def col_rows (cols, row):
         return dict((col, row[col]) for col in cols)

> I don't understand how that lambda expression works.
> For starters where did row come from?

I'd rather ask: where did 'cols' come from? 'row' is the (only) input var of the 
function.

> How did it know it was working on data?

The data it actually works on is 'cols' (reason why it should be explicitely 
written as input var). 'row' is just an index in cols.

Denis

[*] Obscure, partly because (1) such "wild" 'lambda' function defs do not belong 
to Python mainstream coding style and (2) its (of Python) support for such style 
of coding is itself rather unpracticle & unreadable (which probably contributes 
to (1))


More information about the Tutor mailing list