This is the simplest lambda:
f = lambda x: x
I can write. Lambda functions or lambdas originate from functional programming and Lambda calculus. They are very useful when you need to you pass functions as parameters to other functions. You can consider also that lambda is inline or anonymous function.
In this post:
- Simple lambda vs function
- Lambda do operation over list elements
- Python lambda filter
- Python lambda fibonacci
- Python lambda count words lenght
- Python lambda two arguments
- Python lambda and if
Why and when to use lambdas:
- it's fast and easy way to prototype and test your ideas
- sometimes could be easier to be read
- return function from another function
Simple lambda vs function
This is comparison of lambda function to a normal function. Both are powering the number:
f = lambda x: x ** 2
print(f(2))
def f(x):
return x ** 2
print(f(2))
result:
9
9
Lambda do operation over list elements
If you want to do some operations over the elements of a any collection in python you can use lambdas:
mylist = [1,2,3]
print(list(map(lambda x: x ** 2, mylist)))
result:
[1, 4, 9]
Python lambda filter
You can use lambdas to perform filtering over lists as getting all numbers in range which divide to 5:
numbers = range(0, 100)
print (list(filter(lambda x: x % 5 == 0, numbers)))
result:
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
Python lambda fibonacci
Another example with lambda functions and recursion is fibonacci:
fib = lambda x : 1 if x <= 2 else fib(x-1) + fib(x-2)
print(fib(15))
result:
610
Python lambda count words lenght
Let say that you want to do counting of word lenght in a sentence. Then you can use lambda like:
text = 'Lambda functions or lambdas originate from functional programming and Lambda calculus'
wordlist = text.split()
lengths = map(lambda word: word + ': ' + str(len(word)), wordlist)
print (list(lengths))
result:
['Lambda: 6', 'functions: 9', 'or: 2', 'lambdas: 7', 'originate: 9', 'from: 4', 'functional: 10', 'programming: 11', 'and: 3', 'Lambda: 6', 'calculus: 8']
Python lambda two arguments
You can pass more than one argument to lambda function. Below you can find example of lambda function with two parameters:
grCmDiv = lambda x,y: x if y ==0 else not x % y and y or grCmDiv(y , x % y)
print(grCmDiv(112, 28))
result:
28
Python lambda and if
You can use also if in lambda expression. The syntax is different than the normal if operator:
div = lambda x: 'div 5' if x % 5 == 0 else 'no div 5'
print(div(15))
print(div(12))
result:
div 5
no div 5