In Python, lambda
is a keyword that allows you to create small anonymous functions. Anonymous functions are functions that are not bound to a name, and are usually created for a specific purpose, such as being passed as an argument to another function.
Here’s an example of a lambda
function that returns the sum of two numbers:
sum = lambda x, y: x + y result = sum(2, 3) print(result) # Output: 5
In this example, the lambda
keyword is used to define an anonymous function that takes two arguments x
and y
, and returns their sum. We then call this function with the arguments 2 and 3, and assign the result to a variable named result
. Finally, we print out the value of result
, which is 5.
The syntax for a lambda
function is as follows:
lambda arguments: expression
The arguments
are the arguments passed to the function, and the expression
is the operation to be performed on the arguments. The result of the expression is returned by the function. Here’s an example of a lambda
function that squares a number:
square = lambda x: x**2 result = square(4) print(result) # Output: 16
In this example, the lambda
keyword is used to define an anonymous function that takes one argument x
and returns its square. We then call this function with the argument 4, and assign the result to a variable named result
. Finally, we print out the value of result
, which is 16.
lambda
functions are often used in combination with other functions, such as map()
and filter()
. Here’s an example of a lambda
function being used with the map()
function to double the values in a list:
numbers = [1, 2, 3, 4, 5] doubled_numbers = list(map(lambda x: x * 2, numbers)) print(doubled_numbers) # Output: [2, 4, 6, 8, 10]
In this example, the map()
function is used to apply the lambda
function to each element in the numbers
list, and return a new list containing the results. The lambda
function doubles each element in the list.
Another common use case for lambda
functions is to sort a list of objects based on a specific attribute. Here’s an example:
students = [ {'name': 'Alice', 'age': 20}, {'name': 'Bob', 'age': 19}, {'name': 'Charlie', 'age': 21} ] students_sorted_by_age = sorted(students, key=lambda x: x['age']) print(students_sorted_by_age)
In this example, the sorted()
function is used to sort the students
list based on the age
attribute of each student. The lambda
function is used to specify the key to be used for the sort. The x
parameter represents each element in the list, and the x['age']
expression specifies the attribute to be used for the sort.
In summary, lambda
functions are small anonymous functions that can be used for a variety of purposes, such as performing a specific operation on a set of data, passing it as an argument to another function, or sorting a list of objects based on a specific attribute.