Examples of using Lambda Functions in Python 3
( 26 Articles)
A lambda function in Python is a small anonymous function that is defined by using the lambda keyword, like this:
lambda args: expression
A lambda function can take unlimited number of arguments but it is syntactically restricted to a single expression.
For a better feeling and building muscle on using lambda functions, let’s study the following examples together.
Example 1: Simple
This lambda function calculate the sum of three input numbers:
sum = lambda x, y, z : x + y + z print(sum(3, 4, 5))
Corresponding approach if you are using the normal function with the def keyword::
def sum(x, y, z): return x + y + z
Example 2: Lambda + map() function
The map() function in Python returns a map object of the results after applying a given function to each item in an iterable (list, tuple, dictionary, set).
The example below using map() and lambda to create a new list whose elements are the squares of the elements of a given list:
my_list = [1, 2, 3, 4, 5, 6] square_map = map(lambda list_item: list_item * list_item, my_list) square_list = list(square_map) # Convert map object to list print(square_list)
[1, 4, 9, 16, 25, 36]
Example 3: Lambda + reduce() function
Like the map() function, the reduce() function can receive a given function and an iterable as arguments. However, it returns a single value instead of an iterable.
The following example calculates the result from the multiplication of all the elements in a given list:
from functools import reduce my_list = [1, 2, 3, 4, 5, 6] result = reduce(lambda item, total: item * total, my_list) print(result)
We’ve walked through some examples of Python lambda functions. At this point, you should become more familiar in using them in your future programs.
If you would like to learn more interesting stuff about Python, have a look at these articles: Extract all links from a webpage using Python and Beautiful Soup 4 – VS Code: How to comment out a block of Python code – Examples of numpy.linspace() in Python – Most popular String methods in Python – How to run Python 3 with Nodemon on Mac.
You can also check out our Python category page for the latest tutorials and examples.