[Tutor] Applications/examples of some advanced Py features, please !

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri Jan 3 19:47:01 2003


On Fri, 3 Jan 2003, Bob Gailer wrote:

> Regarding lambda, it is an abbreviated way of defining a function. The
> limitation is that the body of the function is one expression whose
> value is returned.
>
> f = lambda x, y:x+y
>
> is the same as
>
> def f(x, y):
>    return x+y

Hi Bob,


Python's lambda expressions are deliberately weakened to force people to
use them only for simple stuff --- Python programs favor giving real names
to functions.  In contrast, in some other languages, like Scheme and
Ocaml, the lambda concept is allowed more expressivity, so lambda is more
prevalent in those languages.



> It is useful when you only need to refer to the function once, as in:
> filter(lambda x:x>5, some-sequence-of-numbers)
>
> That's all I have to say about lambda, except that, if you want to use
> it with list comprehension the syntax is a little tricky:
>
> [(lambda x:x>5)(item) for item in some-sequence-of-numbers]


I think you mean:

    [item for item in some_sequence_of_numbers
     if (lambda x: x>5)(item)]

to do a filtering kind of operation.  But yes, this is pretty darn ugly.
List comprehensions and lambdas don't mix very well, but that's probably
because they're not supposed to.  *grin*



A functional programmer would use the filter() function instead of a list
comprehension:

###
>>> some_sequence_of_numbers = [3,1,4,1,5,9,2,6]
>>> filter(lambda x: x>5, some_sequence_of_numbers)
[9, 6]
###

which, if we cross our eyes funny, can scan as "Filter a list of elements
out of some_sequence_of_numbers, chosen by this particular boolean
function."




Just to contrast with another language, let's see what this might look
like in OCaml:

(*** OCaml code --- the stuff with # in the beginning is what I type. ***)

# let some_sequence_of_numbers = [3;1;4;1;5;9;2;6];;
val some_sequence_of_numbers : int list = [3; 1; 4; 1; 5; 9; 2; 6]

# List.filter (function x -> x > 5) some_sequence_of_numbers;;
- : int list = [9; 6]

(***)

Good, at least we get a similar result.  *grin*



Lambda is pretty much used as a convenient way of writing quicky one-shot
functions for "mapping" and "filtering".  In computer science theory,
they're pretty important --- in the functional-based languages, lambdas
are a fundamental building block of computation --- but in Python, they
play a backstage role: it's often a good thing to just define a new
function using 'def'.


Good luck!