[Tutor] string to list
alan.plum at uni-koeln.de
Thu Feb 11 09:41:40 CET 2010
On Mi, 2010-02-10 at 16:57 +0000, Owain Clarke wrote:
> I would love a really clear explanation of lambda!
Generally, lambdas are anonymous functions.
In Python specifically, however, they are limited to simple expressions
(i.e. only what you can put on the right-hand side of an assignment).
myfunction = lambda <args>: <expression>
is roughly equivalent to:
def myfunction(<args>): return <expression>
(note that the function definition becomes invalid if you leave out the
function name, lambdas OTOH don't need to be assigned to a named
variable and don't contain a name in their definition)
The point here is that the expression is evaluated and the result
returned by the lambda, much like the expression following a return
statement in a normal function: the equivalent function's body consists
of a single return statement with the lambda's body as return value.
There's not much to understanding how lambdas work. They just make
one-offs easier when all you really want to do is pass a value where a
callable is required or if you want to do something like accessing an
index or sub-index or member variable of each object in a list (which is
what the sorting function's key argument is usually used for).
In the case of your code, your lambda was:
lambda x: x
lambda x: x
If applied to a tuple or list, this works like this:
>>> mytuple = ('a','b')
>>> l1 = lambda x: x
>>> l2 = lambda x: x
Hope that helps.
More information about the Tutor