InterviewSolution
| 1. |
One of the 33 keywords of Python is lambda. How and for what purpose is it used? |
|
Answer» The def keyword is used to define a NEW function with a user specified name. Lambda keyword on the other hand is used to CREATE an ANONYMOUS (un-named) function. Usually such a function is created on the fly and meant for one-time use. The general syntax of lambda is as follows: lambda arg1, arg2… : expressionA lambda function can have any number of arguments but there’s always a single expression after : symbol. The value of the expression becomes the return value of the lambda function. For example >>> add=lambda a,b:a+bThis is an anonymous function declared with lambda keyword. It receives a and b and returns a+b.. The anonymous function object is assigned to identifier CALLED add. We can now use it as a regular function call >>> print (add(2,3)) 5The above lambda function is equivalent to a normal function declared using def keyword as below: >>> def add(a,b): return a+b >>> print (add(2,3)) 5However, the body of the lambda function can have only one expression. Therefore it is not a substitute for a normal function having complex logic involving conditionals, loops etc. In Python, a function is a called a first order object, because function can ALSO be used as argument, just as number, string, list etc. A lambda function is often used as argument function to functional programming tools such as map(), filter() and reduce() functions. The built-in map() function subjects each element in the iterable to another function which may be either a built-in function, a lambda function or a user defined function and returns the mapped object. The map() function needs two arguments: map(Function, Sequence(s)) Next example uses a lambda function as argument to map() function. The lambda function itself takes two arguments taken from two lists and returns the first number raised to second. The resulting mapped object is then parsed to output list. >>> powers=map(lambda x,y: x**y, [10,20,30], [1,2,3]) >>> list(powers) [10, 400, 27000]The filter() function also receives two arguments, a function with Boolean return value and an iterable. Only those items for whom the function returns True are stored in a filter object which can be further cast to a list. Lambda function can also be used as a filter. The following program uses lambda function that filters all odd numbers from a given range. >>> list(filter(lambda x: x%2 == 1,range(1,11))) [1, 3, 5, 7, 9] |
|