Theoretical question about Lambda

Lulu of the Lotus-Eaters mertz at gnosis.cx
Mon May 6 02:31:01 EDT 2002


|Alex Martelli wrote:
|> funs = [ (lambda : x) for x in seq ]

Paul Foley <see at below> replied:
|I'd expect that to return a list of as many functions as there are
|items in seq, that all return the last value in seq.  I.e., if seq is
|[1, 2, 3, 4, 5], you'd get 5 functions that all return 5, not
|functions that return 1, 2, 3, 4, and 5 respectively, as I think
|you're expecting

I'm sure the Martellibot was just playing a little joke on readers, to
see if they catch the actual spelling:

    funs = [(lambda x=x: x) for x in seq]

Btw. Foley has slightly misstated what the first one does.  It doesn't
return "the last value in the seq"... except in the sense that listcomps
have (sloppy) side effects in the iterated variables.

What 'funs' really is is a list of functions that return 'x' (whatever
it happens to be at the time of the call).  It need not be called 'x':

    >>> funs = [(lambda : y) for x in seq]
    >>> funs[0]()
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
      File "<stdin>", line 1, in <lambda>
    NameError: global name 'y' is not defined
    >>> y = 22
    >>> funs[0]()
    22

Yours, Lulu...

--
    _/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY: Postmodern Enterprises _/_/_/
   _/_/    ~~~~~~~~~~~~~~~~~~~~[mertz at gnosis.cx]~~~~~~~~~~~~~~~~~~~~~  _/_/
  _/_/  The opinions expressed here must be those of my employer...   _/_/
 _/_/_/_/_/_/_/_/_/_/ Surely you don't think that *I* believe them!  _/_/






More information about the Python-list mailing list