1

Hi I'm trying to learn python and Lambdas and anonymous functions but I'm having a bit problem with the syntax. What i want to do is convert this

def printer():
    print("hello")
    print("world")

to a lambda but i can't seem to get the syntax correctly.

3
  • lambda can only be one line. This is a feature that a lot of people have been asking for for a long time, but I doubt it would be added soon, since that would undermine the reason lambda was added in the first place Commented Apr 15, 2021 at 14:33
  • 1
    @Arandomcoder To be more exact, a lambda can only be a single expression, but it can span multiple lines. Although it is recommended that lambda is only used for rather small, non-complex expressions. Commented Apr 15, 2021 at 14:39
  • 1
    The reason you are struggling is that it shouldn't be done in the first place... This is NOT what lambdas are for... Commented Apr 24, 2021 at 11:43

2 Answers 2

2

Lambdas can only contain a single expression, not a sequence of statements. They are intended for small functions that calculate a value. If your code goes beyonf that, it’s better to write a regular function, not a lambda.

Having said that, in your particular case you can do something like this:

printer = lambda: print("hello\nworld")

or:

printer = lambda: (
    print("hello"),
    print("world")
)

That would work, but it really doesn’t make much sense. The first lambda always returns None, the second returns a tuple of None (you would simply ignore these in your code when calling the lambda).

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

Comments

1

No you cannot, and should not.

Yet if you really need you can some hack like turning several lines into an equivalent single expression

f = lambda x: print("Hello") or print("world")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.