We use the def keyword to define a function in python, followed by a function name and parameters. Let me show you a basic function in python :
In : def my_func (param1) : print(param1) In : my_func('hello')
Let’s see some more examples. We can use the + operator to concatenate the string ‘Hello’ with the input parameter which is name. In case we do not pass any parameter to the function, the output returned is Default Name
In : def my_func (name='Default Name') : print('Hello' + name) In : my_func('Analytics')
In : my_func()
In case we have to return a value in a function after the computing the results, we can do that using the return statement within the function as shown below :
In : def square(num): """ This function squares a number """ return num**2 In : output = square(2) In : output Out: 4
Note the use of double quote is used 3 times to enter comment text within the function. Now that we know the basics of functions, lets move on to map function.
Lets say we have a sequence :
In : seq=[1,2,3,4,5]
If we have to lets say use the above function square to square every number in our sequence above, we can use the map function as shown below :
In : map(square,seq) Out:<map at 0x17ce8b6d550>
The above map is now saved at a memory location. If we have to retrieve the output we will have to cast the map function to a list as shown below :
In : list(map(square,seq)) Out: [1,4,9,16,25]
If you have to rewrite the def function as we discussed above to a much simpler way of computing / calculating desired results we could use the lambda expression:
In : t=lambda(var:var*2) In : t(6) Out: 12
But mostly we will be using the lambda expression in our map function as shown below:
In : seq=[1,2,3] In : list(map(lambda var:var*3,seq)) Out: [3,6,9]
In  statement basically multiplies numbers in the sequence ( seq ) by 3.
Lets take a look at the filter function, as the name suggests the function would retrieve values which are true/satisfied/met.
In : list(filter(lambda: num:num%2 == 0,seq)) Out: 
The modulus function above retrieving a 0 is true only for the integer 2 and false for 1 and 3, hence the output is integer 2.
Let’s move on to methods in python. If you have any questions or suggestions, please let me know in the comments section below.