Kodeclik Blog
Does Python allow multiline lambda functions?
A lambda function is an anonymous function in Python, used often in cases where is not worth the trouble to create a named function using “def” (the usual way we create functions). For instance, when we are trying to sort a list or dictionary by some custom criterion, such a custom criterion is often specified by a lambda function and used in a single line.
Lambda functions can be viewed as “use and throw”, meaning they are used exactly and only at the point they are declared and cannot be re-invoked again and again like regular functions.
Suppose you wish to find the square of a number (e.g., 6) by writing a lambda function. Here is how that might work:
print((lambda x: x*x )(6))
Note the syntax of the above line. We are first creating a function that takes an input (x) and returns the square of x (via x*x). This function (which is unnamed) is then applied on the argument 6, to yield:
36
By creating a lambda function and using it like this we have limited its usage. If we wish to now also compute the square of 7 we need to define and use it again.
Lambda functions are very useful whenever you have functions that expect other functions as inputs, e.g., the map function. The map function takes a function (as one argument) and applies it to every element of an iterable (like a list). Consider the following code to square every element of a list:
print(list(map(lambda x: x*x, [1,2,3])))
The output is:
[1, 4, 9]
Before answering the question of whether Python allows multiline functions, let us try to understand what we mean by multiline functions?
Can a lambda function be split over multiple lines?
Because lambdas are meant to be short and sweet, they are not intended to be elaborate functions. You can split a single line lambda over multiple lines. For instance, you can write:
print(list(map(lambda x:
x*x,
[1,2,3])))
and this will work:
[1, 4, 9]
giving the same output as before.
Can we write a lambda function that has multiple statements or expressions?
The answer to this is a clear No. Let us try to write a lambda function that returns True if a number is even and False if it is odd and use it with our list above, i.e., [1,2,3]
print(list(map(lambda x: if (x%2 == 0):
return "True" else: return "False", [1,2,3])))
The output will be something like:
File "main.py", line 1
print(list(map(lambda x: if (x%2 == 0):
^
SyntaxError: invalid syntax
Note that Python complains about an invalid syntax in our lambda function. This is because the definition of the lambda function has many statements and thus this is a multiline lambda (even though you haven’t split it over multiple lines) and hence disallowed.
In this particular case, there is a way to write it as a single expression, like so:
print(list(map(lambda x:
"True" if (x%2 == 0)
else "False",
[1,2,3])))
Note that the above way of defining a function is considered as a single expression rather than a composite if..else loop, and is thus allowed. Furthermore note that this is split over multiple lines (but is still a single expression). The output is:
['False', 'True', 'False']
as expected.
You can try to be explicit about the fact that the function is split over multiple lines by using continuation characters, like so:
print(list(map(lambda x: \\
"True" if (x%2 == 0) \\
else "False",
[1,2,3])))
This reinforces that this is all a single function and the output is still:
['False', 'True', 'False']
So what is the moral of the story? A lambda function must contain a single expression whether you split it over multiple lines (for ease of readability) or not. Multiline lambdas containing more complex logic is not allowed in Python.
If you liked this blogpost, checkout our blogpost on how to do a max() over Python iterables using lambda functions. Also learn how to nest lambda functions in Python.
For more Python content, checkout the math.ceil() and math.floor() functions! Also
learn about the math domain error in Python and how to fix it!
Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.