As a relative neophyte to Python, could somebody show me an example of
when something like lambda becomes necessary? Its structure and syntax
looks like an anomaly compared to the rest of Python.
Yes, IIRC Guido has claimed it was slipped into the language by a lisp aficionado when he wasn't paying attention. :) I think it's one of the things he wants to get rid of in Python 3K.
The syntax is just the word "lambda", then the variable name(s) you'd like to supply to the function, colon, then the function body. The lambda command returns a function object.
lambda x: x+1
Creates a function that adds 1 to the input.
So try this in a python shell
myadder = lambda x: x+1
myadder(1)
result: 2
Lambda is really handy when put in combination with map and filter. These allow you to write a small function to run over a list and avoid doing "for i in ..." etc..
Map = run the function and put the result in a list
Filter = the function returns a boolean, if true, that item will remain in the list
Return a list with each number incremented by one:
a = [1, 2, 3]
map(lambda x: x+1, a)
result: [2, 3, 4]
Return a list with results less than 3:
a=[1, 2, 3]
filter(lambda x: x<3, a)
result [1,2]
I actually use lambda all of the time and hope it doesn't get removed in Python 3K.
- Chris