skip to Main Content

I would like to do the equivalent of the following in Python:

x = {
    return 1 + 1
}

Is there any way to do this in Python without having to define a whole new function?

i.e. This

x = :
    return 1+1

And not this

def func():
    return 1+1

x = func()

3

Answers


  1. I believe what you’re looking for is a lambda. Although please check that your "JavaScript" does work first (though I think this is the concept you’re asking for).

    For example:

    x = lambda : 1 + 1
    
    print(x())
    

    In this case, x stores your "codeblock," or an anonymous function that you can call.

    Login or Signup to reply.
  2. Use Python lambda functions:
    x = lambda v: return 1 + 1

    Login or Signup to reply.
  3. You can use lambda,which are anonymous functions.

    y=lambda: 1+1
    print(y())
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search