Home > Article > Backend Development > Python Lambda expressions: Make code concise and clear
Lambda expression is an anonymous function in python. It can define a function without defining a function name. The syntax is:
lambda arguments : expression
Among them, arguments are the parameters of the function, and expression is the expression of the function. For example, the following code defines a lambda expression that adds two numbers and returns the result:
lambda x, y: x + y
The main advantages of Lambda expressions are simplicity and anonymity. It lets you define a function without defining its name, which is useful for some simple tasks. For example, the following code uses a lambda expression to square each element in a list:
numbers = [1, 2, 3, 4, 5] squared_numbers = map(lambda x: x ** 2, numbers) print(list(squared_numbers))
The output result is:
numbers = [1, 2, 3, 4, 5] even_numbers = filter(lambda x: x % 2 == 0, numbers) print(list(even_numbers))
The output result is:
[2, 4]
numbers = [1, 2, 3, 4, 5] squared_numbers = map(lambda x: x ** 2, numbers) print(list(squared_numbers))
The output result is:
strings = ["apple", "banana", "cherry", "durian", "elderberry"] sorted_strings = sorted(strings, key=lambda x: len(x)) print(sorted_strings)
The output result is:
["apple", "cherry", "banana", "elderberry", "durian"]
Lambda expressions are a powerful tool that allows you to write cleaner, more readable, and more efficient code. It can be used in a variety of scenarios, including operations such as list filtering, mapping, and sorting. If you want to write cleaner and more efficient code, lambda expressions are a tool worth mastering.
The above is the detailed content of Python Lambda expressions: Make code concise and clear. For more information, please follow other related articles on the PHP Chinese website!