Beyond the Basics: Functions

3.2. Beyond the Basics: Functions#

An example of an advanced fuction can be the lambda function. It is an anonymous function in Python that can be defined in a single line using the lambda keyword. It is typically used for simple and concise operations without the need for a formal function definition.

Here’s an example that showcases the difference between lambda functions and normal functions:

from math import pi 
import os 
# Normal function
def multiply(x, y):
    return x * y

result = multiply(3, 4)
print(result)  # Output: 12

# Lambda function
multiply_lambda = lambda x, y: x * y

result_lambda = multiply_lambda(3, 4)
print(result_lambda)  # Output: 12
12
12

Both the normal function and the lambda function are used to multiply 3 and 4. The results obtained from both approaches are identical (12). The key difference is that the normal function is defined with the def keyword, whereas the lambda function is defined using the lambda keyword without a formal function name.

lambda functions are particularly useful in scenarios where a small, one-time function is needed without the need for a full function definition and name.