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 PlaygroundTags
languagesyntaxcorefunctionfunctional-programming
Related Items
def
Keyword
Defines a new function or method
map()
Built-in Function
Applies a function to every item in an iterable and returns an iterator
filter()
Built-in Function
Returns elements from an iterable for which a function returns True
sorted()
Built-in Function
Returns a new sorted list from any iterable
functools
Stdlib — Functional
Higher-order functions: lru_cache, partial, reduce, wraps, singledispatch