[Tutor] Lambda function, was: Simple counter to determine frequencies of words in adocument

ALAN GAULD alan.gauld at btinternet.com
Tue Nov 23 17:34:12 CET 2010



> OK, all of this is perfectly clear but what is still difficult for  me
> to understand is the following. If you remember the line of code  in
> question was:
> 
> >sorted(word_table.items(), key=lambda item:  item[1], reverse=True)
> 
> This is supposed to return a list of tuples such  as
> 
> [('the', 3), ('in', 1), ('fig', 1)]
> 
> If this list of tuples is  what is in the context, why is item[1]
> referring to the second position in  any tuple and not to the second
> tuple in the list of tuples? I mean, if I  do:

Because sorted() passes each item in the sequence being 
sorted to the function defined in key, like this:

def sorted(seq, key):
     result = []
     for item in seq:
         sortVal = key(item)
         insertItemInResult(item,sortVal,result)
     return result

Notice that it uses key as a function inside sorted.
And lambda creates a function so sorted applies 
the lambda to each item in turn to retrieve the sort key.

> I  guess I'm having trouble figuring out what the scope of the variable
> 'item'  is in this case. Why is tuple[1] in this line of code
> interpreted to mean  "the second position in any of the tuples" and not
> "the second tuple in the  available list of tuples". 

Because item in the lambda is a local variable within the lambda. 
When the lambda is used inside sorted the value of item is 
a single tuple of your sequence.

> Perhaps this is a  very stupid question but it is hard for me 
> to wrap my mind around this. 

It is a biot odd when you aren't used to thinking of function 'objects' 
that can be passed around like data and then executed. But it is 
a very powerful technique once you get your head wrapped around it.

[ FWIW Languages like C do the same thing with the concept of a 
  pointer to a function. ]

HTH,

Alan G.



More information about the Tutor mailing list