Re: lambda in list comprehension acting funny

Discussion in 'Python' started by Daniel Fetchinson, Jul 11, 2012.

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

    >
    > Just the way Python lambda expressions bind their variable
    > references. Inner 'i' references the outer scope's 'i' variable and not
    > its value 'at the time the lambda got defined'.
    >
    >
    >> And more importantly, what's the simplest way to achieve the latter? :)

    >
    > Try giving the lambda a default parameter (they get calculated and
    > have their value stored at the time the lambda is defined) like this:
    > funcs = [ lambda x, i=i: x**i for i in range( 5 ) ]


    Thanks a lot!
    I worked around it by

    def p(i):
    return lambda x: x**i
    funcs = [ p(i) for i in range(5) ]

    But your variant is nicer (matter of taste of course).

    Cheers,
    Daniel


    --
    Psss, psss, put it down! - http://www.cafepress.com/putitdown
     
    Daniel Fetchinson, Jul 11, 2012
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. philoso
    Replies:
    5
    Views:
    493
    Sudsy
    Nov 21, 2003
  2. Vedran Furac(
    Replies:
    4
    Views:
    357
    Marc 'BlackJack' Rintsch
    Dec 19, 2008
  3. Daniel Fetchinson

    lambda in list comprehension acting funny

    Daniel Fetchinson, Jul 11, 2012, in forum: Python
    Replies:
    45
    Views:
    734
    Robert Miles
    Aug 16, 2012
  4. Daniel Fetchinson

    Re: lambda in list comprehension acting funny

    Daniel Fetchinson, Jul 11, 2012, in forum: Python
    Replies:
    4
    Views:
    227
    88888 Dihedral
    Jul 14, 2012
  5. Jurko Gospodnetić

    Re: lambda in list comprehension acting funny

    Jurko Gospodnetić, Jul 11, 2012, in forum: Python
    Replies:
    0
    Views:
    218
    Jurko Gospodnetić
    Jul 11, 2012
Loading...

Share This Page