What is a lambda function in Python?

A lambda function is a small function without a name (an anonymous function) that is written in a single line using the lambda keyword. The syntax is lambda arguments: expression, and the value of the expression is returned automatically.

square = lambda x: x * x
add = lambda a, b: a + b

print(square(5))
print(add(2, 3))

names = ["Robin", "Al", "Maria"]
print(sorted(names, key=lambda n: len(n)))

Output:

Tutorials Class - Output Window

25
5
['Al', 'Robin', 'Maria']

Lambdas are mostly used for short, one-time work, like the key of sorted() or inside map() and filter(). For anything longer, a normal def function is easier to read. See Python Lambda for more.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.