Lambda Function

What Is a Lambda Function?

  • A lambda function is a small, anonymous function in Python. It can take any number of arguments but can only have one expression.

Syntax:

  • The syntax for a lambda function is:

    python
    lambda arguments: expression
    
  • The expression is executed and the result is returned.

Examples:

  1. Simple Lambda Function:
    • Add 10 to argument a and return the result:

      python
      x = lambda a: a + 10
      print(x(5))  # Output: 15
      
  2. Multiple Arguments:
    • Multiply argument a with argument b:

      python
      x = lambda a, b: a * b
      print(x(5, 6))  # Output: 30
      
    • Summarize arguments a, b, and c:

      python
      x = lambda a, b, c: a + b + c
      print(x(5, 6, 2))  # Output: 13
      

Why Use Lambda Functions?

  • Lambda functions are particularly useful as anonymous functions inside other functions. For example, they can be used to create functions that multiply a given number by an unknown number:

    python
    def myfunc(n):
        return lambda a: a * n
    
    mydoubler = myfunc(2)
    print(mydoubler(11))  # Output: 22
    
    mytripler = myfunc(3)
    print(mytripler(11))  # Output: 33
    

More Examples:

  1. Lambda Function with No Arguments:
    • A lambda function that returns a fixed value:

      python
      six = lambda: 6
      print(six())  # Output: 6
      
  2. Recursive Lambda Function:
    • A lambda function to calculate the factorial of a number:

      python
      factorial = lambda a: a * factorial(a - 1) if a > 1 else 1
      print(factorial(5))  # Output: 120
      
  3. Returning a Lambda Function:
    • A function that returns a lambda function:

      python
      def myfunc(n):
          return lambda a: a ** n
      
      square = myfunc(2)
      cube = myfunc(3)
      
      print(square(3))  # Output: 9
      print(cube(3))    # Output: 27
      

Exercises:

  1. Simple Calculation:
    • Write a lambda function that adds 5 to a given number.

      python
      add_five = lambda x: x + 5
      print(add_five(10))  # Output: 15
      
  2. Conditional Lambda:
    • Write a lambda function that returns "Even" if a number is even, and "Odd" if a number is odd.

      python
      check_even_odd = lambda x: "Even" if x % 2 == 0 else "Odd"
      print(check_even_odd(7))  # Output: Odd
      
  3. Lambda in a Function:
    • Create a function that takes a number and returns a lambda function to multiply any given number by that number.

      python
      def multiplier(n):
          return lambda x: x * n
      
      times_three = multiplier(3)
      print(times_three(5))  # Output: 15
      

Summary:

  • Lambda functions in Python are concise, anonymous functions that are useful for small, quick operations. Practice creating and using lambda functions to get comfortable with this powerful feature!