lambda

KeywordPython 2.0+Intermediate

Creates a small anonymous (unnamed) function in a single expression

Quick Info

Documentation
Official Docs
Python Version
2.0+

Learn by Difficulty

Quick Example

python
square = lambda x: x ** 2
print(square(5))

add = lambda a, b: a + b
print(add(3, 4))

# Lambda with built-in functions
numbers = [5, 2, 8, 1, 9, 3]
print(sorted(numbers))
print(sorted(numbers, key=lambda x: -x))

words = ["banana", "apple", "cherry"]
print(sorted(words, key=lambda w: len(w)))

lambda creates a function in one expression. It is most useful as a key function for sorted(), map(), filter(), etc.

Try in Playground

Tags

languagesyntaxcorefunctionfunctional-programming

Related Items