Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use value of variable in lambda expression [duplicate]

Tags:

python

lambda

a = [] a.append(lambda x:x**0) 
a.append(lambda x:x**1)

a[0](2), a[1](2), a[2](2)... spits out 1, 2, 4, ...

b=[]
for i in range(4)
    b.append(lambda x:x**i)

b[0](2), b[1](2), b[2](2)... spits out 8, 8, 8, ...

In the for loop, the i is being passed to lambda as a variable, so when I call it, the last value of i is used instead of the code running as it does with a[]. (ie b[0] should use x^1, b[1] should use x^2, ...)

How can I tell lambda to pick up the value of i instead of the variable i itself.

like image 461
Emrah Diril Avatar asked Apr 17 '09 14:04

Emrah Diril


People also ask

Can lambda return 2 values?

That's not more than one return, it's not even a single return with multiple values. It's one return with one value (which happens to be a tuple).

Can we change the lambda expression variable data?

Yes, you can modify local variables from inside lambdas (in the way shown by the other answers), but you should not do it.

How do you use variables in lambda function?

To set environment variables in the Lambda consoleOpen the Functions page of the Lambda console. Choose a function. Choose Configuration, then choose Environment variables. Under Environment variables, choose Edit.

How are variables used outside of lambda expression?

Because the local variables declared outside the lambda expression can be final or effectively final. The rule of final or effectively final is also applicable for method parameters and exception parameters. The this and super references inside a lambda expression body are the same as their enclosing scope.


1 Answers

Ugly, but one way:

for i in range(4)
    b.append(lambda x, copy=i: x**copy)

You might prefer

def raiser(power):
    return lambda x: x**power

for i in range(4)
    b.append(raiser(i))

(All code untested.)

like image 111
Darius Bacon Avatar answered Nov 15 '22 06:11

Darius Bacon