[Python] problem with lambda in list comprehension over a list of functions [duplicate]

Discussão em 'Python' iniciado por Stack, Março 20, 2025.

  1. Stack

    Stack Membro Participativo

    Is this a bug, or is it supposed to do that?

    def example_function(x,flag):
    if flag=='a':
    print('a:',x)
    elif flag=='b':
    print('b:',x)

    flambda_list=[lambda x : example_function(x,'a'),
    lambda x : example_function(x,'b')]

    fllc=[ (lambda x : f(x)) for f in flambda_list]

    fllc[0](0.1)
    fllc[1](0.2)


    which outputs:

    b: 0.1
    b: 0.2


    Note that in contrast if I do:

    flambda_list[0](0.1)
    flambda_list[1](0.2)


    it outputs:

    a: 0.1
    b: 0.2


    as expected. I also tried a more direct approach:

    flaglist=['a','b']
    flc = [ (lambda x : example_function(x,p)) for p in flaglist ]

    flc[0](0.1)
    flc[1](0.2)


    and this also prints:

    b: 0.1
    b: 0.2


    what is it that am I misunderstanding in the use of lambda functions inside list comprehension?

    The fact that it is 'b' and not 'a' suggests me that it uses some kind of pointer and it is the last value that gets passed around.

    Continue reading...

Compartilhe esta Página