- Python Lambda
- Lambda Function Definion
- Calling the Lambda Function
- Lambda Functions With Mutiple Arguments
- High order Functions
- Python lambda and Regular Functions
- Lambda function Restrictions
- Statements inside Lambda Function
- Type Annotation
- *args and **kwargs in Python Lambda
- Decorator in Python Lambda Function
- Python lambda with map and filter
- Python map
- Python filter
- Decorators in lamda with Python map
- Testing Python Lambda with Unittest
- Python Programming 101 — Lambda | Map | Filter | Reduce | *args and **kwargs
- Lambda Function
- Map
- Filter
- Reduce
- Example of Map, Filter and Reduce:
- *args vs **kwargs
Python Lambda
The lambdas are anonymous one line functions in Python that can be used to perform tasks which don’t require regular Python functions. Some of the most useful features of Python lambdas are.
- Lambda function can take any number of arguments
- Lambda functions are very short although can be very encryptic
- Lambda functions can be used to return function objects
- Lambda functions are restricted to only a single expression
Below snippet shows the basic syntax of a Python function. The below function takes «argument» and returns it back.
# normal function that returns a value def functionName(argument): return argument
Lambda Function Definion
Example of above function «functionName» using Lambda
lambda argument : argument
Note the syntax of the above function. Lambda functions have no name. They are defined and used on the fly. We can’t reuse them in the form defined above. The first ‘argument’ is the argument of the function and the 2nd ‘argument’ is the returned value.
Example: — Lambda function that returns the twice of the given input.
But you must be wondering, how to provide the input to above lambda function!
Calling the Lambda Function
To use the function, you can surround it with parenthesis and provide the parameters between paranthesis as shown below.
# (lambda x: x * 2 )(5) = lambda 5 : 5 * 2 = 5 * 2 = 10
There is another way to provide an argument to the lambda function. We can assign the lambda function to a variable and then pass the argument to that variable as shown below.
double = lambda x : x * 2 # and call it like so : double(5)
Ofcourse above lambda function and below function are equivalent.
# the function double is equivalent to : def double(x): return x * 2
Lambda Functions With Mutiple Arguments
Python Lambda functions can have multipe parameters separated by commas (,) here is an example.
pairs = lambda x , y : "P( x = "+str(x)+" , y = "+ str(y)+" )" pairs(1,2)
There is a shorthand way of calling Python lambdas function that is without assigning a name to the function.
There will be no conflict and you can call the above lambda function with the arguments like this.
Note the underscore in the above syntax. Underscore refers to the lambda function that we just described above.
Ofcourse, you can use IIFE ( Immediately Invoked Function Expression ) syntax too.
High order Functions
We can use function inside lambda. Below snippet is an example of lambda function inside another lambda function.
# we can use a function as a parameter of lambda : myfunction = lambda param , func : param + func(param) # and call it like so : myfunction(3,lambda x : x**2)
In the above snippet, we passed outer lambda function two parameters — param and another lambda function (func)
myfunction(4,lambda x : x - 1)
Python lambda and Regular Functions
import dis div = lambda x,y : x / y type(div)
2 0 LOAD_FAST 0 (x) 2 LOAD_FAST 1 (y) 4 BINARY_TRUE_DIVIDE 6 RETURN_VALUE
# applaying same thing for a normal function: import dis def div(x,y): return x / y type(div)
4 0 LOAD_FAST 0 (x) 2 LOAD_FAST 1 (y) 4 BINARY_TRUE_DIVIDE 6 RETURN_VALUE
Lambda function Restrictions
Lambda functions throws similar errors as Python regular functions do. For example, below snippet will throw string multiplication error «can’t multiply sequence by non-int of type ‘str'»
type_error = lambda str1,str2 : str1 * str2 type_error("hello","world")
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) in 1 type_error = lambda str1,str2 : str1 * str2 ----> 2 type_error("hello","world") in (str1, str2) ----> 1 type_error = lambda str1,str2 : str1 * str2 2 type_error("hello","world") TypeError: can't multiply sequence by non-int of type 'str'
Statements inside Lambda Function
We can’t add statments in lambda function as shown below.
File "", line 1 (lambda x : assert x > 0)(1) ^ SyntaxError: invalid syntax
However we can use parenthesis to achieve the statement effect.
In below snippet, note expression (x>0 and + or ‘-‘) would translate to if x > 0 then return ‘+’ otherwise return ‘-‘
Type Annotation
Hinting doesn’t work on lambda functions. It only works on normal functions.
Below regular Python function takes ‘string’ and ‘integer’ as two parameters but returns output as string.
def function(param:str,i : int)-> str: return param * str(i)
In lambda function, if you specify type hints, you will end up getting a syntaxError.
lambda param:str , i : int : param * i
File "", line 1 lambda param:str , i : int : param * i ^ SyntaxError: invalid syntax
*args and **kwargs in Python Lambda
As we described above in the ‘multiple arguments section’ of this post, Python lambda function can take multiple arguments but lambda functions can also take arguments using *arg and **kwargs
(lambda p1 , p2 , p3 : (p1 + p2 + p3)/3)(1,2,3)
(lambda p1 , p2 , p3 = 3 : (p1 + p2 + p3)/3)(1,2)
(lambda *args : sum(args)/len(args))(1,2,3)
(lambda **kwargs : sum(kwargs.values())/len(kwargs))(one = 1, two = 2, three = 3)
Python lambdas initialize arguments example
(lambda p1 , p2=0 , p3=0 : (p1 + p2 + p3)/3 ) ( 1 , p2=2 , p3=3)
Decorator in Python Lambda Function
Let us see first, how decorators in regular Python functions work. Here is an example.
# Defining a decorator def trace(f): def wrap(*args, **kwargs): print(f"[TRACE] function name: , arguments: , kwargs: ") return f(*args, **kwargs) return wrap # Applying decorator to a function @trace def double(x): return x * 2 # Calling the decorated function double(3)
[TRACE] function name: double, arguments: (3,), kwargs: <>
Check out below example of application of decorator to a lambda function. Notice in the below snippet, how we have wrapped the lambda function inside the trace decorator function. Order of brackets is very important.
[TRACE] function name: , arguments: (3,), kwargs: <> 6
Python lambda with map and filter
Lambda is regularly used with built-in functions like map or filter.
Python map
map iterates the function through a list or set. The function could be regular Python function or lambda function.
In the below example,lambda function x: x + 5 is applied on list of numbers (0,4)
list(map(lambda x : x + 5 ,range(5)))
Python filter
In the below example,lambda function x: x > 0 is applied on list of numbers [-5,-2,1,0,3,5]
list(filter(lambda x : x>0,[-5,-2,1,0,3,5]))
Decorators in lamda with Python map
In below snippet, map() is taking two arguments. The first one is the decorator function around lambda function i.e.
trace(lambda x: x * 2) and second argument is range(3).
The map() will run the decorated lambda function 3 times as shown below.
list(map(trace(lambda x: x * 2), range(3)))
[TRACE] function name: , arguments: (0,), kwargs: <> [TRACE] function name: , arguments: (1,), kwargs: <> [TRACE] function name: , arguments: (2,), kwargs: <>
Testing Python Lambda with Unittest
import unittest double = lambda x : x * 2 class Test(unittest.TestCase): def test_1(self): self.assertEqual(double(1),2) def test_2(self): self.assertEqual(double(2),4) def test_10(self): self.assertEqual(double(10),11) # this test will fail if __name__ == '__main__': unittest.main(verbosity=2)
double = lambda x : x * 2 double.__doc__ = """Doubles the number entred in the parameters : >>> double(1) 2 >>> double(2.0) 4.0 >>> double(10) 20 """ if __name__ == '__main__': import doctest doctest.testmod(verbose=True)
Trying: double(1) Expecting: 2 ok Trying: double(2.0) Expecting: 4.0 ok Trying: double(10) Expecting: 20 ok 16 items had no tests: __main__ __main__.Test __main__.Test.test_1 __main__.Test.test_10 __main__.Test.test_2 __main__._16 __main__._2 __main__._3 __main__._9 __main__.div __main__.function __main__.functionName __main__.myfunction __main__.pairs __main__.trace __main__.type_error 1 items passed all tests: 3 tests in __main__.double 3 tests in 17 items. 3 passed and 0 failed. Test passed.
Python Programming 101 — Lambda | Map | Filter | Reduce | *args and **kwargs
Written By Random Skool
Before starting the tutorial it’s my humble request to join our telegram channel and group.
In this tutorial, we will learn about one of the interesting topics that play a vital role in python programming .i.e. lambda function. Lambda functions change the definition of traditional functions that we are using in our day to day life.
However, with the help of the lambda function, we are able to cover the three subtopics such as map, filter, and reduce.
Lambda Function
Lambda function can be called as anonymous/one-liner function.
How lambda function can be useful?
1. Lambda can be useful when we want to write a function in a compact way or in a one-liner.
2. Lambda function can be useful when we want the function to be part of another function. Or we can say that when we want one function to pass arguments to another function where we can use lambda function.
Let’s understand the paradigm of a lambda function using an example.
This code explains the compact nature of the lambda function. You can see that in the code first in the case of traditional or regular python function what are the required steps are necessary for writing code 1. Need to define the function using def keyword (def function_name(parameter)) 2. Under the function, the definition needs to write the statement or body of the function. 3. Last step function calling and parameter passing. The whole python regular function is the three-step process and we can reduce at times when we need some compact structured way using lambda function.
In Lambda function, we are declaring only variable and after that using the lambda keyword we are writing the actual working of code and at last, we are passing the parameter. That’s how simple the lambda function is.
Let’s see another example of the lambda function.
In this example, we are using another concept of lambda function in which we are passing the lambda function parameter to another function. We are using two variables and taking input from the user of multiplicand and multiplier using type casting for converting a string to an int type. And after that passing multiplier value to lambda function and multiplicand value to the regular function and use those two values for general multiplication. With the help of this example, we all are aware that we can lambda python function in parameter passing also.
Map
A map is used to apply a function in every element in a list.
Properties:
1. Works with regular or lambda function
2. Takes list as an argument
3. Provide a modified list
Filter
A filter is used for filtering the list for which the functions returns true.
Properties:
1. Works with regular or lambda function
2. Takes list as an argument
3. Filter the list by applying a certain condition is true.
Reduce
A Reduce is used for reducing the list by performing repetition operations over the pairs of lists. Reduce comes under the functools module.
1. Works with regular or lambda function
2. Takes list as an argument
3. Reduce the list
4. Using functools module
Example of Map, Filter and Reduce:
*args vs **kwargs
Important Point (Both are used when we are dealing with unpredictable datasets or value)
*args — It is used to pass a big list of argument or unpredictable list of argument
**kwargs — keyword argument
Working of both *args and **kwargs are same only major difference between both of them is when are dealing with a list of elements we need to use *args and when we are dealing with keyword argument such as dictionaries like data-type we need to use **kwargs.
Let’s discuss with the help of an example.
In this example, we are declaring two functions with different parameters set one for a list of arguments and one for keyword argument. The syntax is self-explanatory all we are using simple python function syntax for parameter passing and function calls except when we are passing a simple list of arguments we are using *args and when we are passing keyword argument dictionary like we are using **kwargs.
Different Scenario of using *args and **kwargs:
1. Both can be used in the same function with a different function call
2. Both can be used in the same function with the same function call
Note:
We have to follow the concept of ordering while using *args and **kwargs both strictly follow the nature of the order.
First (Normal Parameter) > Second (*args) > Third (**kwargs)
In the next tutorial, we will study decorators, enumerate functions, join, and Indexing/Slicing.
Click here for the next tutorial.
For Complete Python Programming 101 tutorial series ( Click here ).
For Queries and Contact there are multiple ways:
1. From telegram search @randomskoolQnA and @randomskool
2. From Contact Us Page
3. From Comment
For Daily Updates Please subscribe to the feed.
For Job-related Updates Please fill the subscriber feedback form.