In the previous segments, you saw how to take two lists and perform an element-wise subtraction. Wouldn’t this be better if you had a Python function similar to the sum() or max() function defined in Python, where you could give lists as an input and get the desired result? By the end of this segment, you would be able to do that.
Syntax of a function:
Often programmers get confused while passing parameters to a function. Let us understand that in detail in the next video.
You heard about arguments and parameters a couple of times in the video and might have got confused. Function parameters are the variables used while defining the function, and the values used while calling this function are the function arguments.
There are four types of function parameters:
Required parameters: These parameters are necessary for the function to execute. While calling an inbuilt max() function, you need to pass a list or dictionary or other data structure. This means that a sequence is a required parameter for this function.
Default arguments: These parameters have a default value and will not throw any error if they are not passed while using the function.
Keyword parameters: These parameters are expected to be passed using a keyword. In the example of printing a list, you saw that passing end = ',' prints the elements of the list separated by a comma instead of the default newline format. This is a classic example of a keyword argument, the value of which is changed by using the end keyword and specifying the value.
Variable-length parameters: These enable the function to accept multiple arguments. Now, let’s try to write a function that takes two lists as the input and performs an element-wise subtraction. It is simple: first, you define your function with two parameters:
def fun(L1,L2):
Now, from your previous experience, you know how to perform element-wise subtraction. So, you just need to put this inside the function definition:
def list_diff( list1,list2): list3=[] for i in range(0,len(list1)): list3.append(list1[i]-list2[i]) return list3 L1 = [10,20,30,24,18] L2 = [8,14,15,20,10] list_diff(L1,L2)
Note: The return statement is very crucial in the whole function definition, as it is responsible for returning the output of the function.
Lambda functions are another way of defining functions to execute small functionalities occurring while implementing a complex functionality. These functions can take multiple parameters as input but can only execute a single expression; in other words, they can only perform a single operation.
The format of a lambda expression is as follows:
function_name = lambda <space> input_parameters : output_parameters
For example: diff = lambda x,y : x-y is a lambda function to find the difference of two elements.
Having learnt this, let’s look at another example of a lambda function.