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.
In questa pagina del sito puoi guardare il video online Lambda Function in Python della durata di ore minuti seconda in buona qualità , che l'utente ha caricato Rakesh Patel 15 febbraio 2024, condividi il link con amici e conoscenti, su youtube questo video è già stato visto 26 volte e gli è piaciuto 3 spettatori. Buona visione!