What are Python Functions?
A function is a collection of related assertions that performs a mathematical,
analytical, or evaluative operation. A collection of statements called Python
Functions returns the particular task. Python functions are simple to define
and essential to intermediate-level programming. The exact criteria hold to
function names as they do to variable names. The goal is to group up certain
often performed actions and define a function. We may call the function and
reuse the code contained within it with different variables rather than
repeatedly creating the same code block for different input variables.
User-defined and built-in functions are the two main categories of functions
in Python. It helps maintain the programme concise, unique, and well-
structured.
Advantages of Functions in Python
Python functions have the following Perks.
By including functions, we can prevent repeating the same code block
repeatedly in a program.
Python functions, once defined, can be called many times and from
anywhere in a program.
If our Python program is large, it can be separated into numerous functions
which is simple to track.
The key accomplishment of Python functions is we can return as many
outputs as we want with different arguments.
However, calling functions has always been overhead in a Python program.
Syntax of Python Function
# An example Python Function
def function_name( parameters ):
# code block
The following elements make up to define a function, as seen above.
The beginning of a function header is indicated by a keyword called def.
function_name is the function's name that we can use to separate it from
others. We will use this name to call the function later in the program. In
Python, name functions must follow the same rules as naming variables.
We pass arguments to the defined function using parameters. However, they
are optional.
The function header is terminated by a colon (:).
We can use a documentation string called docstring in the short form to
explain the purpose of the function.
The body of the function is made up of several valid Python statements. The
indentation depth of the whole code block must be the same (usually 4
spaces).
We can use a return expression to return a value from a defined function.
Example of a User-Defined Function
We will define a function that when called will return the square of the number passed to it as an
argument.
Code
# Example Python Code for User-Defined function
def square( num ):
"""
This function computes the square of the number.
"""
return num**2
object_ = square(6)
print( "The square of the given number is: ", object_ )
Output:
The square of the given number is: 36
Calling a Function
A function is defined by using the def keyword and giving it a name, specifying the arguments that must
be passed to the function, and structuring the code block.
After a function's fundamental framework is complete, we can call it from anywhere in the program. The
following is an example of how to use the a_function function.
Code
# Example Python Code for calling a function
# Defining a function
def a_function( string ):
"This prints the value of length of string"
return len(string)
# Calling the function we defined
print( "Length of the string Functions is: ", a_function( "Functions" ) )
print( "Length of the string Python is: ", a_function( "Python" ) )
Output:
Length of the string Functions is: 9
Length of the string Python is: 6
The Anonymous Functions
These types of Python functions are anonymous since we do not declare them, as we declare usual
functions, using the def keyword. We can use the lambda keyword to define the short, single output,
anonymous functions.
Lambda expressions can accept an unlimited number of arguments; however, they only return one value
as the result of the function. They can't have numerous expressions or instructions in them. Since
lambda needs an expression, an anonymous function cannot be directly called to print.
Lambda functions contain their unique local domain, meaning they can only reference variables in their
argument list and the global domain name.
Although lambda expressions seem to be a one-line representation of a function, they are not like inline
expressions in C and C++, which pass function stack allocations at execution for efficiency concerns.
Syntax
Lambda functions have exactly one line in their syntax:
lambda [argument1 [,argument2... .argumentn]] : expression
Below is an illustration of how to use the lambda function:
Code
# Python code to demonstrate ananymous functions
# Defining a function
lambda_ = lambda argument1, argument2: argument1 + argument2;
# Calling the function and passing values
print( "Value of the function is : ", lambda_( 20, 30 ) )
print( "Value of the function is : ", lambda_( 40, 50 ) )
Output:
Value of the function is : 50
Value of the function is : 90
We'll understand what they are, how to execute them, and their syntax.
What are Lambda Functions in Python?
Lambda Functions in Python are anonymous functions, implying they don't have a name. The def
keyword is needed to create a typical function in Python, as we already know. We can also use the
lambda keyword in Python to define an unnamed function.
Syntax of Python Lambda Function
lambda arguments: expression
This function accepts any count of inputs but only evaluates and returns one expression.
Lambda functions can be used whenever function arguments are necessary. In addition to other forms
of formulations in functions, it has a variety of applications in certain coding domains. It's important to
remember that according to syntax, lambda functions are limited to a single statement.
Example of Lambda Function in Python
An example of a lambda function that adds 4 to the input number is shown below.
Code
# Code to demonstrate how we can use a lambda function
add = lambda num: num + 4
print( add(6) )
Output:
10
The lambda function is "lambda num: num+4" in the given programme. The parameter is num, and the
computed and returned equation is num * 4.
There is no label for this function. It generates a function object associated with the "add" identifier. We
can now refer to it as a standard function. The lambda statement, "lambda num: num+4", is nearly the
same as:
Code
def add( num ):
return num + 4
print( add(6) )
Output:
10
What's the Distinction Between Lambda and Def Functions?
Let's glance at this instance to see how a conventional def defined function differs from a function
defined using the lambda keyword. This program calculates the reciprocal of a given number:
Code
# Python code to show the reciprocal of the given number to highlight the difference between def() and
lambda().
def reciprocal( num ):
return 1 / num
lambda_reciprocal = lambda num: 1 / num
# using the function defined by def keyword
print( "Def keyword: ", reciprocal(6) )
# using the function defined by lambda keyword
print( "Lambda keyword: ", lambda_reciprocal(6) )
Output:
Def keyword: 0.16666666666666666
Lambda keyword: 0.16666666666666666
The reciprocal() and lambda_reciprocal() functions act similarly and as expected in the preceding
scenario. Let's take a closer look at the sample above:
Both of these yield the reciprocal of a given number without employing Lambda. However, we wanted
to declare a function with the name reciprocal and send a number to it while executing def. We were
also required to use the return keyword to provide the output from wherever the function was invoked
after being executed.
Using Lambda: Instead of a "return" statement, Lambda definitions always include a statement given at
output. The beauty of lambda functions is their convenience. We need not allocate a lambda expression
to a variable because we can put it at any place a function is requested.
Using Lambda Function with filter()
The filter() method accepts two arguments in Python: a function and an iterable such as a list.
The function is called for every item of the list, and a new iterable or list is returned that holds just those
elements that returned True when supplied to the function.
Here's a simple illustration of using the filter() method to return only odd numbers from a list.
Code
Using Lambda Function with filter()
The filter() method accepts two arguments in Python: a function and an iterable such as a list.
The function is called for every item of the list, and a new iterable or list is returned that holds just those
elements that returned True when supplied to the function.
Here's a simple illustration of using the filter() method to return only odd numbers from a list.
Code
# Code to filter odd numbers from a given list
list_ = [34, 12, 64, 55, 75, 13, 63]
odd_list = list(filter( lambda num: (num % 2 != 0) , list_ ))
print(odd_list)
Output:
[55, 75, 13, 63]
Using Lambda Function with map()
A method and a list are passed to Python's map() function.
The function is executed for all of the elements within the list, and a new list is produced with elements
generated by the given function for every item.
The map() method is used to square all the entries in a list in this example.
Code
#Code to calculate the square of each number of a list using the map() function
numbers_list = [2, 4, 5, 1, 3, 7, 8, 9, 10]
squared_list = list(map( lambda num: num ** 2 , numbers_list ))
print( squared_list )
Output:
[4, 16, 25, 1, 9, 49, 64, 81, 100]
Using Lambda Function with if-else
We will use the lambda function with the if-else block.
Code
# Code to use lambda function with if-else
Minimum = lambda x, y : x if (x < y) else y
print(Minimum( 35, 74 ))
Output:
35