Lambda expressions does what a function does without the need to properly define the function using def
.
The body of a lambda expression will be similar to what we will put into the return
of a function defined with def
.
Let's take a look at an example using a multiplication function.
Since this function only has return
we can even write it in 1 line.
To simplify that even further, we can use the lambda expression.
lambda x: x*20
You may notice that if you simply run the lambda expression you will get
<function __main__.<lambda>(x)>
This isn't very helpful. So in order to make use of a lambda expression, we assign it a variable.
Now you might be asking, why are we using this lambda expression instead of a normal function?
This is because there are times when you only need to use the function once so you do not have to define it formally.
For example, if we want to use the filter function.
You are expected to comply with University policies and guidelines namely, Appropriate Use of Information Resources Policy, IT Usage Policy and Social Media Policy. Users will be personally liable for any infringement of Copyright and Licensing laws. Unless otherwise stated, all guide content is licensed by CC BY-NC 4.0.