Lambda
Unlike other languages, functions can be used as variables in Python. We have the option to either use functions without defining them beforehand, or define them without using a full def
statement, using Lamba expressions. This is the syntax:
lambda <arguments>: <return from arguemnts>
For example, let's add 1 to an existing number using the usual method:
def add(x):
return x+1
result = add(2)
print(result)
This will output:
3
Now, let's do it with a Lambda expression:
result = (lambda x: x+1)(2)
print(result)
This will output:
3
That is all we have to use! So easy! Now, the question is, How can this help? What is the relevance? The importance of Lambda is that we can use functions as arguments, without defining them.
Lets consider the simple example of counting the number of characters in each word in a sentence.
sentence = 'I like to study Python on Altcademy'
>>> noOfwords = sentence.split()
>>> print noOfwords
>>> lengthOfChar = map(lambda word: len(word), words)
>>> print lengthOfChar
This results in:
['I', 'like', 'to', 'study', 'Python', 'on', 'Altcademy']
[2, 2, 7, 4, 3, 4]