Python Advanced: How to use Lambda Function with python Methods

Home /

Table of Contents

Lambda Anonymous Function

The anonymous nature of Python lambda functions indicates that functions without a name. As we already know, the def keyword is used to define a typical function in Python. In Python, the lambda keyword is used to declare an anonymous function.

The argument list is a comma-separated list of arguments, and the expression is an arithmetic expression that makes use of these arguments. You can name the function by assigning it to a variable.

This function accepts any number of inputs but only evaluates and returns one expression. Lambda functions can be used wherever function objects are necessary. You must remember that lambda functions are syntactically limited to a single expression. Aside from other forms of expression in functions, it has a variety of purposes in specific domains of programming.

The lambda operator, often known as the lambda function, is a method for creating small anonymous functions, or functions without a name. These are throw-away functions, which means they are only needed where they were generated. Lambda functions are typically combined with the functions filter(), map(), and reduce(). Python’s lambda feature was implemented in response to requests from Lisp writers.

Example:

Uppercase_Normal = 'I LOVE PYTHON'
 
Lowercase_Reverse = lambda string: string.lower()[::-1]
 
string = Lowercase_Reverse(Uppercase_Normal)
print(string)

Output:

nohtyp evol i

Here, 

On each iteration of the list comprehension, a new lambda function with the default parameter x is created (where x is the current item in the iteration). Later, within the for loop, we use item() to call the same function object with the default argument and receive the required value. As a result, Constructed_evens() saves a list of lambda function objects.

Multiple statements are not allowed in lambda functions, but we can construct two lambda functions and then call one of them as a parameter to another lambda function. Let’s use lambda to discover the second maximum element.

Some Practical Examples of uses of the lambda function

Example:

# Some Practical Example of uses of lambda function
 
print("List by Lambda")
start_arg = 5
stop_arg = 15
Constructed_Evens = [lambda arg=x: arg * 2 for x in range(start_arg, stop_arg+1)]
for val in Constructed_Evens:
   print(val())
print("-----------------------")
 
 
print('Condition with lambda: ', end='')
print('Find the maximum value between( p, q)')
Maximum = lambda p, q : p if(p > q) else q
print(Maximum(111, 222))
print("-----------------------")
 
 
print('Multiple statements with lambda: ', end='')
print('Find the maximum values from each dimension of list.')
multidimensional_list = [[21,23,25],[22, 24, 26, 28],[27, 29]]
sortList = lambda item: (sorted(i) for i in item)
maximum = lambda item, f : [y[len(y)-1] for y in f(item)]
final_value = maximum(multidimensional_list, sortList)
print(final_value)

Output:

List by Lambda
10
12
14
16
18
20
22
24
26
28
30
-----------------------
Condition with lambda: Find the maximum value between( p, q)
222
-----------------------
Multiple statements with lambda: Find the maximum values from each dimension of list.
[25, 28, 29]

Filter Method

Python’s filter() method accepts a function and a list as inputs. This provides an easy method for filtering out all of the items of a sequence “sequence” for which the function returns True. Here’s a little program that retrieves the odd numbers from a list of numbers.

Example:

print("Even numbers from a list:")
numbers = [23, 67, 24, 98, 56, 24, 72, 33, 99, 54]
filtered_even = list(filter(lambda x: (x % 2 == 0), numbers))
print(filtered_even)

Output:

Even numbers from a list:
[24, 98, 56, 24, 72, 54]

If x is even, lambda x: (x% 2 == 0) returns True or False. Because filter() only maintains items that return true, it discards any items that return false.

Map with lamda

Python’s map() method accepts a function and a list as arguments. The function is called with a lambda function and a list, and it returns a new list containing all of the lambda-changed items returned by that function for each item. 

Example:

print("Divide by 2 from the list:")
numbers = [23, 67, 24, 98, 56, 24, 72, 33, 99, 54]
output = list(map(lambda x: x//2 if (x%2==0) else (x+1)//2 , numbers))
print(output)

Output:

Divide by 2 from the list:
[12, 34, 12, 49, 28, 12, 36, 17, 50, 27]

Reduce with lambda

Python’s reduce() method accepts a function and a list as arguments. A lambda function and an iterable are used to invoke the function, and a new reduced result is returned. This is a repeating procedure over the iterable’s pairs. Reduce() is a function in the functools package.

Example:

from functools import reduce
orginal_list = [921, 23, 555, 66, 12]
 
print("Find Maximum by reduce: ", end='')
Max = reduce(lambda p, q: p if p > q else q, orginal_list)
print(Max)
print('--------------------')
 
print("Summation by reduce: ", end='')
sum = reduce((lambda p, q: p + q), orginal_list)
print(sum)

Output:

Find Maximum by reduce: 921
--------------------
Summation by reduce: 1577

Lambda functions are an important feature of Python, which allows you to create small, anonymous functions that can be used in a variety of contexts. One of the main benefits of using lambda functions is that they can simplify your code and make it more readable. In Python, lambda functions are typically used in situations where a simple function is needed, such as when working with list comprehensions, map(), and filter() functions, and in situations where you need to pass a function as an argument to another function.

Lambda functions are also useful in functional programming, where you might need to pass a function as an argument to another function, or when you want to return a function as a result of another function. In these situations, lambda functions can help to keep your code concise and easy to read.

Another advantage of lambda functions is that they can be used to create closures, which are functions that retain the values of the variables in the enclosing function’s scope. This can be useful when you need to create a function that can be used repeatedly with different values, but where you want to retain some state information between calls.

Lambda functions are a powerful tool in Python that can help to simplify your code, make it more readable, and make it easier to work with functions in a variety of contexts. While they may take some time to get used to, once you understand how they work, you’ll find that they can be an invaluable tool in your programming toolbox.

Share The Tutorial With Your Friends
Twiter
Facebook
LinkedIn
Email
WhatsApp
Skype
Reddit
Other Recommended Article