Lambda Function in Python

Published: 15 February 2024
on channel: Rakesh Patel
26
3

Lambda expressions, also known as anonymous functions or lambda functions, are small, anonymous functions defined using the "lambda" keyword in Python. They are typically used when you need a simple function for a short period, and you don't want to go through the process of defining a named function using the "def" keyword.

The syntax of a lambda expression is as follows:
lambda arguments: expression


Here, "arguments" are the input parameters of the function, and "expression" is the operation performed by the function. Lambda functions can take any number of arguments but only have one expression.

Here are some examples to illustrate the use of lambda expressions in Python:

1. Simple addition:

add = lambda x, y: x + y
print(add(3, 5)) # Output: 8


2. Square of a number:

square = lambda x: x ** 2
print(square(4)) # Output: 16


3. Sorting a list of tuples based on the second element:

points = [(1, 2), (3, 1), (5, 3), (7, 2)]
points.sort(key=lambda point: point[1])
print(points) # Output: [(3, 1), (1, 2), (7, 2), (5, 3)]


4. Filtering even numbers from a list:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4, 6, 8, 10]


5. Using lambda with map:

numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x ** 2, numbers))
print(squared_numbers) # Output: [1, 4, 9, 16, 25]


Lambda expressions are handy when you need to pass a simple function as an argument to another function, such as "map()", "filter()", "sorted()", etc. However, they should be used judiciously, as overuse of lambda expressions can lead to code that is difficult to read and maintain.


On this page of the site you can watch the video online Lambda Function in Python with a duration of hours minute second in good quality, which was uploaded by the user Rakesh Patel 15 February 2024, share the link with friends and acquaintances, this video has already been watched 26 times on youtube and it was liked by 3 viewers. Enjoy your viewing!