In Python, we can use if statements to add conditions our lambda expressions. We can create if, elif, and else blocks in a Python lambda expression easily.
lambda_expression = lambda x: True if x > 0 else False
In Python, lambda expressions are very useful for creating anonymous functions which can be applied on variables or collections of objects.
When using lambda functions in Python, we need to understand that the lambda construct is limited to expressions only.
We can use if statements in Python lambda expressions easily.
Given an if condition, the syntax for using if in lambda expression is:
lambda <arguments> : <statement1> if <condition> else <statement2>
For example, let’s say you want to remove the last character of a string if the string starts with the letter ‘a’.
We can define a lambda expression with an if statement which checks if the string’s first character is ‘a’, and then returns the appropriate string.
Then, we will use map() to apply our lambda expression to every element in the list of strings.
Below is an example of using if with a lambda expression in Python.
list_of_strings = ["apple","banana","avocado","pear","lime","lemon","artichoke"] list_after_lambda = list(map(lambda x: x[:-1] if x == 'a' else x, list_of_strings)) print(list_after_lambda ) #Output: ['appl', 'banana', 'avocad', 'pear', 'lime', 'lemon', 'artichok']
As you can see, all of the strings which begin with ‘a’ have had their last letter removed.
Using if and else in a Multiple Condition Python Lambda Expression
You can define more complex expressions using multiple cases in a Python lambda function which is identical to if, elif and else in a regular function.
Let’s say we want to check a number of conditions in a list of numbers. We can define a multiple condition lambda function a structure similar to if, elif, and else.
To define a multiple condition lambda function, we can use a similar structure as above, where the value for the if condition comes before the if condition.
lambda <args> : <statement1> if <condition > else ( <statement2> if <condition> else <statement3>)
Below is an example of a multiple condition lambda expression applied to a list of numbers in Python.
list_of_numbers = [0,4,2,5,9,1,10,15,14,8,2] list_after_lambda = list(map(lambda x: x**2 if x < 3 else (x*4 if x < 8 else x), list_of_numbers)) print(list_after_lambda) #Output: [0, 16, 4, 20, 9, 1, 10, 15, 14, 8, 4]
Hopefully this article has been useful for you to learn how to use if in lambda functions in your Python code.