In my previous articles (links are below), I have explained "functions". There is a similar way to run some code when needed. It is called "lambda" expression. In this article, I will explain, what lambda is, how to use it, and how to call it.
Prerequisites:
Lambda:
Lambda is an expression that can do similar things with "function". Lambda can only return one expression. It means you can only write one line of commands. Lambda expression is more restrictive than Python functions. To define a lambda expression we use the "lambda" command.
Code:
>>>lambda x: x + 1
This is the syntax for defining lambda. We need to call lambda expression as we do in functions. But as you can see there is no name for a lambda expression. To be able to call the lambda expression we need to assign it to a variable. Lambda always returns the expression.
Code:
>>>techsody = lambda x: x + 1
>>>techsody(5) #single argument.
Output:
6
Let´s do another example.
Code:
>>>total = lambda x,y,z: x*y+z
>>>total(2,5,10) #multi arguments.
Output:
20
You see how short and efficient it is. As, functions, if there is theree parameters, you have to pass exactly there arguments. Lambda is simple and most often used with some other functions such as: map() and filter().
map(): Map function runs a function for eash iterable. Used together with lists.
Code:
>>>l = list(map(lambda x: x.upper(), ['i', 'love', 'techsody']))
>>>print(l)
Output:
['I', 'LOVE', 'TECHSODY']
In this example, we took a lambda function and run it over the list. This usage of map and lambda is commonly used.
filter: Filter function, filters the list based on what you want to see.
Code:
>>>l = list(filter(lambda x: (x%2 == 0), [23, 45, 3463, 3, 2334, 232]))
>>>print(l)
Output:
[2334, 232]
As you can see, I only filtered and printed even numbers in my list.