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?

  • 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. – Brian61354270 Feb 23 '20 at 19:26
  • @Brian okay thanks for the info thats what i thought –  Feb 23 '20 at 19:27
  • 1
    You can use the returned value. `avg=o(1,2)`. – Ch3steR Feb 23 '20 at 19:28
  • What do you mean with "use it later in the lambda expression"? – Kelly Bundy Feb 23 '20 at 19:29
  • @HeapOverflow I meant if avg=x+y then I could do avg*5 later in the expression so I don't have to type out x+y over and over every time I want to do something with them. But if I can't assign them a variable to x+y then i'd have to type x+y every single time. –  Feb 23 '20 at 19:31
  • 1
    If you showed an actual example with that usage, people might be willing to show how to make it work. – Kelly Bundy Feb 23 '20 at 19:37
  • 1
    it's possible with Python 3.8 assignment expressions. – juanpa.arrivillaga Feb 23 '20 at 19:40
  • As an aside, you *should not be assigning lambdas to names*. That defeats *their only advantage*, which is to by anonymous. If you are going to do that, just use a full function definition – juanpa.arrivillaga Feb 23 '20 at 19:54

1 Answers1

5

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.

gilch
  • 10,813
  • 1
  • 23
  • 28