Python: Lambda
Lambda is used to define a function. Aka anonymous function.
💡 TIP:
python lambda body must be in a single line.
Usually for simple functions.
If you need more than one line, use def
.
〔see Python: Function〕
# lambda with one arg # a function that adds 1 print((lambda x: x + 1)(3)) # 4
# lambda with two args # a function that adds two numbers print((lambda x, y: x + y)(3, 4)) # 7
# give lambda a name ff = lambda x: x + 1 print(ff(3)) # 4
# add 2 numbers ff = lambda x, y: x + y print(ff(3, 4)) # 7
lambda is often used with
map
or
filter.
xx = [1, 2, 3, 4, 5] # keep just even numbers yy = filter(lambda x: x % 2 == 0, xx) print(list(yy)) # [2, 4]
Python, Function and Class
python lambda problem
- Python: Lambda
- The fate of reduce in Python 3000 (2005)
- Python, Lambda, Guido: is Language Design Just Solving Puzzles? (2006)
- The Fate of Lambda in Python 3000 and Scheme v300 (2010)
- Why Python Lambda is Broken and Cannot be Fixed (2013)
- Xah Talk Show 2021-05-28 Why Python Lambda is Broken and Can't be Fixed