Python Lambda is a small anonymous function that can take any number of arguments, but can only have one expression. It is a way to create small, one-time-use functions without having to define them in the traditional way. Lambda functions are often used in functional programming, where functions are treated as first-class citizens.
The syntax for a lambda function is simple. It starts with the keyword "lambda", followed by the arguments, separated by commas, and then a colon. After the colon, the expression to be evaluated is written. The result of the expression is then returned.
Here is an example of a lambda function that takes two arguments and returns their sum:
<p>x = lambda a, b : a + b</p>
<p>print(x(5, 10)) # Output: 15</p>
The above code creates a lambda function that takes two arguments, "a" and "b", and returns their sum. The function is then called with the arguments 5 and 10, and the result is printed to the console.
Lambda functions can also be used as arguments to other functions. This is often seen in functions like "map", "filter", and "reduce". Here is an example of using a lambda function with "map" to square a list of numbers:
<p>numbers = [1, 2, 3, 4, 5]</p>
<p>squared = list(map(lambda x: x**2, numbers))</p>
<p>print(squared) # Output: [1, 4, 9, 16, 25]</p>
The above code creates a list of numbers, and then uses the "map" function to apply a lambda function to each element of the list. The lambda function takes one argument, "x", and returns its square. The result is a new list with the squared values.
Another common use of lambda functions is in sorting. The "sorted" function can take a lambda function as its "key" argument, which is used to determine the order of the elements. Here is an example of using a lambda function to sort a list of tuples by the second element:
<p>students = [("Alice", 23), ("Bob", 19), ("Charlie", 21)]</p>
<p>sorted_students = sorted(students, key=lambda x: x[1])</p>
<p>print(sorted_students) # Output: [("Bob", 19), ("Charlie", 21), ("Alice", 23)]</p>
The above code creates a list of tuples, where each tuple contains a student's name and age. The "sorted" function is then used to sort the list by the second element of each tuple, which is the age. The lambda function takes one argument, "x", which is a tuple, and returns the second element of the tuple.
Overall, lambda functions are a powerful tool in Python for creating small, one-time-use functions. They can be used in a variety of contexts, including as arguments to other functions, in functional programming, and in sorting.