In this article we will discuss how to use if , else if and else in a lambda functions in  Python. Will also explain how to use conditional lambda function with filter() in python.

Using if else in Lambda function

Using if else in lambda function is little tricky, the syntax is as follows,

For example let’s create a lambda function to check if given value is between 10 to 20 i.e.

Here we are using if else in a lambda function, if given value is between 10 to 20 then it will return True else it will return False. Now let’s use this function to check some values i.e.

Output:

Creating conditional lambda function without if else

Well using ‘if’ ‘else’ keywords makes things easy to understand, but in lambda we can avoid using if & else keywords and still achieve same results. For example let’s modify the above created lambda function by removing if else keywords & also True False i.e.

This lambda function does the same stuff as above i..e checks if given number lies between 10 to 20. Now let’s use this function to check some values i.e.

Output:

Using filter() function with a conditional lambda function (with if else)

filter() function accepts a callback() function and a list of elements. It iterates over all elements in list and calls the given callback() function
on each element. If callback() returns True then it appends that element in the new list. In the end it returns a new list of filtered elements only.

Suppose we have a list of numbers i.e.

Now let’s use filter() function to filter numbers between 10 to 20 only by passing a conditional lambda function (with if else) to it i.e.

Output:

it uses the passed lambda function to filter elements and in the end returns list of elements that lies between 10 to 20,

Using if, elif & else in a lambda function

Till now we have seen how to use if else in a lambda function but there might be cases when we need to check multiple conditions in a lambda function. Like we need to use if , else if & else in a lambda function. We can not directly use elseif in a lambda function. But we can achieve the same effect using if else & brackets i.e.

Let’s see how to do that,

Create a lambda function that accepts a number and returns a new number based on this logic,

  • If the given value is less than 10 then return by multiplying it by 2
  • else if it’s between 10 to 20 then return multiplying it by 3
  • else returns the same un-modified value

Let’s use this lambda function,

Output:

Complete example is as follows,

Output:

Join LinkedIn Group of Python Professional Developers who wish to expand their network and share ideas.

You can also follow us On Twitter :

Click Here to Subscribe for more Articles / Tutorials like this.