def increment(n): return lambda x: x + n increment_by_5 = increment(5) print(increment_by_5(6))
Here, the increment_by_5 function will increment a given number by 5. So, increment_by_5(6) will return the following:
11
Similarly, using the same function increment, we can define another function, say increment_by_6 in the following way:
def increment(n): return lambda x: x + n increment_by_6 = increment(6) print(increment_by_6(6))
So, the program will print the following output:
12
As we can see, we can write a function increment() and use a lambda function within that function. And then, we can use the increment() function to define our own functions.
Similarly, we can write a multiply() function and use a lambda function within that function. And then, we can use the multiply() function to define our own function, say tripler().
def multiply(n): return lambda x: x * n tripler = multiply(3) print(tripler(7))
The above program will print the following output:
21
These are some simple uses of the lambda function. We can also use this function in some complex scenarios. For example, let’s say there is a list of numbers and we want to separate out the odd numbers from the list and create another list of odd numbers from the numbers that are contained in the first list. One way to solve the problem is to use the filter() function. The …






0 Comments