[Tutor] Lambda function, was: Simple counter to determine frequencies of words in adocument
ALAN GAULD
alan.gauld at btinternet.com
Mon Nov 22 10:20:25 CET 2010
> What I don't understand is the nature of the term 'item'. Is it a
> variable?
Yes, its just a descriptive name. You could have used x just
as easily, Python doesn't know, nor care.
It is just like in defining any normal function
def f(x): return x
is exactly the same as:
def f(data): return data
data is just a different name for the input parameter.
> refers generically to members of some collection but it does not look
> like it is some built-in name in Python.
Correct, the name 'item' has been used to be descriptive of what
kind of thing the lambda is processing. In this case an item from
the collection to be sorted.
> 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?
When you specify a parameter you create a variable.
def f(data): return data
creates a local variable called data within my function f.
> to understand how Python does it. Does python know because the only
> thing that word_table.items() contains is a list of tuples
No, it knows because you defined the variable 'item' before the colon
lambda item : item[1]
So Python looks at the name(s) before the colon and uses
them within the expression following the colon.
You can have multiple names (or none) before the colon,
try:
>>> f = lambda : 6 # no parameters
>>> f()
6
>>> g = lambda a,b : a+b # two parameters
>>> g(2,3)
5
>>> cube = lambda sillyName: sillyName**3
>>> cube(3)
27
> this particular context? Would this work if instead of item[1] the
> code said foobar[1]?
only if you specified foobar before the colon!
> 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?
Absolutely true.
You may like to track down a (library?) copy of Wesley Chun's book
Core Python. It does a very good job of explaining to beginners
what Python is up to internally. In my opinion its the best book for
those beginners who like to "peer under the hood".
HTH,
Alan G.
Author of the Learn to Program site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list