lambda in list comprehension acting funny

Franck Ditter franck at ditter.org
Thu Jul 12 08:49:58 CEST 2012


In article <mailman.2007.1341988993.4697.python-list at python.org>,
 Daniel Fetchinson <fetchinson at googlemail.com> wrote:

> > funcs = [ lambda x: x**i for i in range( 5 ) ]
> > print funcs[0]( 2 )
> > print funcs[1]( 2 )
> > print funcs[2]( 2 )
> >
> > This gives me
> >
> > 16
> > 16
> > 16
> >
> > When I was excepting
> >
> > 1
> > 2
> > 4
> >
> > Does anyone know why?

In Python 3.x :

funcs = [lambda x: x**i for i in range(5)]
list(map(lambda f: f(2),funcs)) --> [16, 16, 16, 16, 16]

Ooops, cool semantics :-)

In Racket Scheme (http://racket-lang.org), they seem to know lambdas :

#lang racket

;;; quick and dirty list comprehension syntax as a macro, for fun :

(define-syntax-rule (list-of expr for x in L)     
  (map (lambda (x) expr) L))

(list-of (sqr x) for x in (range 5)) --> (0 1 4 9 16)

(define funcs (list-of (lambda (x) (expt x i)) for i in (range 5)))
(map (lambda (f) (f 2)) funcs) --> (1 2 4 8 16)

    franck



More information about the Python-list mailing list