0

How can I assign a variable inside a lambda expression?

So for example I have lambda function like this.

o = lambda x,y: x+y

I want x+y to equal another variable so I can use it later in the lambda expression.

o= lambda x,y: avg = x+y #this thorws an error

I tried reading up on lambda documentation but nothing helps.

If I can make a variable, how would I use it later?

8
  • 2
    No. Lambdas must evaluate to an expression. You cannot include any statements, such as assignments. If you need use a statement, create a local function. Commented Feb 23, 2020 at 19:26
  • @Brian okay thanks for the info thats what i thought Commented Feb 23, 2020 at 19:27
  • 1
    You can use the returned value. avg=o(1,2). Commented Feb 23, 2020 at 19:28
  • 1
    If you showed an actual example with that usage, people might be willing to show how to make it work. Commented Feb 23, 2020 at 19:37
  • 1
    it's possible with Python 3.8 assignment expressions. Commented Feb 23, 2020 at 19:40

1 Answer 1

6

Yes, with the new := "walrus" assignment operator, you can make assignments in an expression, including in lambdas. Note that this is a new feature requiring Python 3.8 or later.

lambda x, y: (avg:=x+y)

There are ways to simulate this operator on older versions of Python as well, but := is the proper way to do it now.

Sign up to request clarification or add additional context in comments.

7 Comments

The proper way to "simulate" it before was to just use a regular function definition :)
I tried this. avg=0;a=lambda x,y:(avg:=x+y);print(avg) still prints 0.
@Ch3steR You never called the lambda, so why did you expect the assignment to happen?
It was a typo I called a(1,2);print(avg).
@Ch3steR the avg is scoped inside the lambda, same as a normal assignment in a function definition. Maybe you were expecting a nonlocal? You can't do nonlocal assignments in lambdas. If you put the print inside the lambda, it would work.
|