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

Josep M. Fontana josep.m.fontana at gmail.com
Mon Nov 22 09:56:27 CET 2010


Thanks Alan and Emile,

>> By the way, I know what a lambda function is and I read about the key
>> parameter in sorted() but I don't understand very well what
>> "key=lambda item: item[1]" does.
...
>> ....What I don't understand is the syntax of "item : item[1]".
>
...
Alan says:
> So reverse engineering that we get
>
> lambda item: item[1]
>
> item is the parameter of the anonymous function.
> and item[1] is the return value. (The colon separates parameter
> from return value)

Emile says:

>Key defines a lambda function that accepts as a single passed parameter named item and >returns the element in position [1] thereof.

OK, the explanation is very clear. I guess what confuses me here is
the use of the term 'item' and here I'm going to reveal my greenness
in Python and programming in general.

So, I know the term 'item' is used in general to refer to the
different elements that are part of a collection. Thus an item in a
dictionary would be a dictionary "entry" of the type {x:y}, an item in
a list would be any of the elements that can be a member of a list (a
digit, a string, another list, etc.). In this case, an item would be a
tuple of the form (word, x) and so item[1] refers to x. Since the key
parameter indicates which term is supposed to be used for comparison
in the sorting, in this case the result will be that the sorting will
be done according to the digits in that position. So, that much is
clear.

What I don't understand is the nature of the term 'item'. Is it a
variable? Is it some kind of built-in  "term" (it cannot be a built-in
data type since it refers to elements of different data types)? I
checked the Python books I have and did some googling and the only
uses I find of 'item' are generic uses where it is clear that 'item'
refers generically to members of some collection but it does not look
like it is some built-in name in Python.

I mean, since the first time 'item' is mentioned is within the lambda
function, how does Python know that item[1] refers to the second
position of the tuple? If it is a variable, where is it defined? I see
how you get to that conclusion through human reasoning but I'm trying
to understand how Python does it. Does python know because the only
thing that word_table.items() contains is a list of tuples and
therefore X[1] can only refer to the second position in the tuple in
this particular context? Would this work if instead of item[1] the
code said foobar[1]?

Understanding the inner workings of Python (or programming languages
in general) can help me (and anybody) become better at this. Do you
see what I mean?

Josep M.


More information about the Tutor mailing list