Jose Vu - 2 months ago 6

Python Question

I just switched to Python from Matlab, and I want to use lambda function to map function

`f1(x,y)`

`f2(x)`

I want that when I map the function

`f2(x) <- f1(x,y=y1)`

`y`

`y1`

`>>> def f1(x,y):`

>>> return (x+y)

>>> y1 = 2

>>> f2 = lambda x: f1(x,y1)

>>> f2(1)

3

I expect

`f2(1)`

`3`

`y1`

`y1`

`f1(1)`

`>>> y1 = 5`

>>> f2(1)

6

I wonder is there a way that when I declare

`f2 = lambda x: f1(x,y1)`

`f1`

`y1`

`f2`

I'm still new to Python, please help, much appreciate.

Answer

Try:

```
f2 = lambda x, y=y1: f1(x,y)
```

Your issue has to do with how closures work in Python

Your version of the lambda function will use the current version of `y1`

. You need to *capture* the value of `y1`

on the line where you've defined the lambda function. To do that, you can define it as the default value of a parameter (the `y=y1`

part).