Difference between Normal def defined function and Lambda
In this article, we will discuss the difference between normal 'def' defined function and 'lambda' function in Python.
Def keyword
In Python, functions defined using def keyword are commonly used due to their simplicity. Unlike lambda functions, which always return a value, def functions do not return anything unless explicitly specified. They must be declared within a namespace and can perform various tasks, including handling multiple conditions, using nested loops, printing output, importing libraries and raising exceptions. Example:
# Define function using def keyword
def calculate_cube_root(x):
try:
return x**(1/3)
except:
return "Invalid Input"
print(calculate_cube_root(27)) # calling the function
Output
3.0
In the above code, we define a function using the def keyword that takes a single number as input and returns its cube root. If the input is not a real number, it returns "Invalid Input."
Lambda keyword
Lambda functions are small, anonymous functions defined using the lambda keyword. Unlike normal functions created with def, lambda functions do not have a name and are typically used for short, simple operations. They can take multiple arguments but can only contain a single expression, which is evaluated and returned. Let's define the same function as discussed in the above example using lambda keyword to have a better understanding of the difference between them.
# Define function using lambda keyword
cube_root= lambda x: x**(1/3)
print(cube_root(27)) # Calling the function
Output
3.0
Notice that the same result can be achieved using a lambda function. However, lambda functions are typically used when we need to define short, anonymous functions for simple operations.
Table of Difference Between def and Lambda
Feature | def Function | lambda Function |
---|---|---|
Definition | Defined using the def keyword | Defined using the lambda keyword |
Function Name | Requires a name (unless inside another function) | Anonymous (no name unless assigned to a variable) |
Number of Expressions | Can have multiple expressions and statements | Can have only a single expression |
Readability | More readable, especially for complex logic | Less readable for complex operations |
Return Statement | Uses return explicitly to return a value | Implicitly returns the result of the expression |
Use Case | Used for defining reusable functions with multiple operations | Used for short, throwaway functions |
Supports Loops and Conditions | Can include loops, multiple conditions, and multi-line statements | Can only contain a single expression, no loops |
Code Complexity | Suitable for complex functions | Best for simple, one-liner functions |
Assignment to Variable | Defined independently with a function name | Can be assigned to a variable for reuse |