Home > Backend Development > Python Tutorial > Python Lambda expressions: Make code concise and clear

Python Lambda expressions: Make code concise and clear

王林
Release: 2024-02-19 15:15:18
forward
1124 people have browsed it

Python Lambda表达式:让代码简洁明了

Introduction to Lambda expressions

Lambda expression is an anonymous function in python. It can define a function without defining a function name. The syntax is:

lambda arguments : expression
Copy after login

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
Copy after login

Advantages of Lambda expressions

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))
Copy after login
Copy after login

The output result is:

numbers = [1, 2, 3, 4, 5]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers))
Copy after login

The output result is:

[2, 4]
Copy after login
  • List mapping: Each element in a list can be easily mapped to a new value using lambda expressions. For example, the following code uses a lambda expression to square each element in the list:
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(lambda x: x ** 2, numbers)
print(list(squared_numbers))
Copy after login
Copy after login

The output result is:

strings = ["apple", "banana", "cherry", "durian", "elderberry"]
sorted_strings = sorted(strings, key=lambda x: len(x))
print(sorted_strings)
Copy after login

The output result is:

["apple", "cherry", "banana", "elderberry", "durian"]
Copy after login

Conclusion

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!

source:lsjlt.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template