Is there anything like a "void lambda" in Python?

dictionary, lambda, python, python-2.7, void

Solution

The contents of a lambda function must be a single expression; no statements are allowed. Moreover, `print` is a statement in Python 2.x. This means that you cannot use it inside a lambda.

If you want to use the Python 3.x `print` function, you can import it from `__future__` like so:

# Add this line to the top of your script file
from __future__ import print_function

Now, `print` can be used inside lambdas because it is a function:

statement = {
    "Bob": lambda: print("Looking good, Bob!"),
    "Jane": lambda: print("Greetings, Jane!"),
    "Derek": lambda: print("How goes it, Derek?")
}[person]()

Problem

That is, a lambda that takes no input and returns nothing. I was thinking of clever ways to mimic switch statements in Python. Here's what I attempted (to no avail): ``` statement = { "Bob": lambda: print "Looking good, Bob!", "Jane": lambda: print "Greetings, Jane!", "Derek": lambda: print "How goes it, Derek?" }[person]() ```

Original source

Related problems