Is there a way of assigning lambda to a function?

Question:

I need to assign the lambda function to a variable, and use it later in the script for small protection. Is that possible?

For example, I´ll assign the lambda function to a variable named foo:

foo = lambda

then, when I need it, I would use it this way or another:

foo2 = foo x: x*x

is this possible?

Asked By: River

||

Answers:

lambda is a keyword and not an object. you have to define the function and save that as a variable.

The usage of lambda is quite straightforward though, as you have already done it with the print. Try this –

foo = lambda x: x.upper()

foo('hello world')
'HELLO WORLD'

EDIT: (Based on OPs comments) Here is a great SO answer that talks about why you can’t change the keyword lambda with a variable name, being a reserved python keyword.

The OP mentioned these reserved keywords in the answer –

False      await      else       import     pass
None       break      except     in         raise
True       class      finally    is         return
and        continue   for        *lambda*     try
as         def        from       nonlocal   while
assert     del        global     not        with
async      elif       if         or         yield
Answered By: Akshay Sehgal
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.