ANONYMOUS (LAMBDA) FUNCTIONS IN PYTHON

 ANONYMOUS (LAMBDA) FUNCTIONS IN PYTHON

  • A lambda function is a small, unnamed function used with a single expression.
  • In Python, it is used with the `lambda` keyword, so it is known as lambda expressions.
  • It can take any number of arguments but can only have one expression.

 Syntax:

lambda arguments: expression

 

Features:-

  •  A quick and simple function.
  • Anonymous: They don't have a name like regular functions defined with def.
  • Compact: Defined in a single line, making them concise for small operations.
  • Created with lambda: Use the lambda keyword followed by arguments and an expression.
  • Single expression: Can only contain a single expression, which is evaluated and returned.
  • No return statement: The expression's value is automatically returned.
  • Can take any number of arguments.
  • Can be used anywhere a function is expected.

 

Example:

add = lambda x, y: x + y  # Adds two numbers

result = add(5, 3)        # Calls the lambda function

print(result)             # Output: 8

 

Example: simple function

def add(x, y):

    return x + y

# Equivalent lambda function

add_lambda = lambda x, y: x + y

 

# Using the lambda function

result = add_lambda(3, 5)

print(result)  # Output: 8

 

Example:- Using lambda with map

numbers = [1, 2, 3, 4, 5]

squared = list(map(lambda x: x**2, numbers))

print(squared) 

 

Output: [1, 4, 9, 16, 25]

 

# Using lambda with filter

even_numbers = list(filter(lambda x: x % 2 == 0, numbers))

print(even_numbers) 

 

Output: [2, 4]

 

Uses:

Need a simple, one-time function.

Need to pass a function as an argument to another function.

Need to improve code readability for concise operations.

Lambda functions are commonly used with functions like `map()`, `filter()`, and `sorted()`:

 

Drawback:-

Not useful for complex logic or multiple statements, use regular def functions.

Not useful for reuse in multiple places, a named function is more readable.

 

Post a Comment

0 Comments