Python Tutorial

Python Variable

Python Operators

Python Sequence

Python String

Python Flow Control

Python Functions

Python Class and Object

Python Class Members (properties and methods)

Python Exception Handling

Python Modules

Python File Operations (I/O)

Python lambda expressions (anonymous functions)

Lambda expressions in Python are used to create small, anonymous functions. They can be useful in situations where you need a simple function for a short period of time and don't want to define a full function using the def keyword. Here's a tutorial on lambda expressions in Python:

  • Basic Syntax

Lambda expressions are defined using the lambda keyword, followed by a list of arguments, a colon, and a single expression. The lambda function can take any number of arguments but can only have one expression.

lambda arguments: expression
  • Using lambda expressions

Here's an example of a lambda expression that takes two arguments and returns their sum:

add = lambda a, b: a + b
print(add(3, 4))  # Output: 7

In this example, we create a lambda function that adds two numbers and assign it to the variable add. We can then call the lambda function just like a regular function.

  • Lambda functions in higher-order functions

Lambda expressions are often used with higher-order functions like map(), filter(), and sorted(). These functions take a function as an argument, and a lambda function can be used inline for this purpose.

Example with map():

numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x ** 2, numbers))

print(squares)  # Output: [1, 4, 9, 16, 25]

Example with filter():

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

print(even_numbers)  # Output: [2, 4]

Example with sorted():

names = ["Alice", "bob", "Charlie", "david"]
sorted_names = sorted(names, key=lambda x: x.lower())

print(sorted_names)  # Output: ['Alice', 'bob', 'Charlie', 'david']
  • Limitations of lambda functions

Lambda functions have some limitations compared to regular functions defined with the def keyword:

  • They can only have one expression, meaning they cannot contain multiple statements or include complex logic.
  • They don't have a name and can't be easily reused, which can make debugging more difficult.
  • They can be harder to read, especially for people who are not familiar with lambda functions.

In summary, lambda expressions in Python allow you to create small, anonymous functions. They can be useful for simple tasks or when used with higher-order functions like map(), filter(), and sorted(). However, lambda functions have some limitations, and it's important to use them judiciously to maintain code readability and maintainability.

  1. How to use lambda functions in Python:

    • Description: Define small, anonymous functions using the lambda keyword for short-term use.
    • Code:
      add = lambda x, y: x + y
      result = add(3, 5)
      
  2. Creating anonymous functions with lambda in Python:

    • Description: Lambda functions are anonymous functions without a formal name.
    • Code:
      greet = lambda name: f"Hello, {name}!"
      message = greet("Alice")
      
  3. Functional programming with lambda functions in Python:

    • Description: Use lambda functions in functional programming paradigms, treating functions as first-class citizens.
    • Code:
      square = lambda x: x**2
      numbers = [1, 2, 3, 4]
      squared_numbers = map(square, numbers)
      
  4. Using lambda with map(), filter(), and reduce() in Python:

    • Description: Apply lambda functions with built-in functions like map(), filter(), and reduce() for concise operations.
    • Code:
      numbers = [1, 2, 3, 4, 5]
      squared_numbers = map(lambda x: x**2, numbers)
      even_numbers = filter(lambda x: x % 2 == 0, numbers)
      sum_all = reduce(lambda x, y: x + y, numbers)
      
  5. Lambda functions and variable scoping in Python:

    • Description: Understand the scoping rules for variables within lambda functions.
    • Code:
      x = 10
      square = lambda y: y**2 + x
      result = square(5)  # x is accessible from the outer scope
      
  6. Lambda functions in list comprehensions in Python:

    • Description: Embed lambda functions within list comprehensions for concise and expressive code.
    • Code:
      numbers = [1, 2, 3, 4]
      squared_numbers = [(lambda x: x**2)(num) for num in numbers]
      
  7. Lambda functions and sorting in Python:

    • Description: Utilize lambda functions as key functions for custom sorting in Python.
    • Code:
      students = [("Alice", 25), ("Bob", 20), ("Charlie", 22)]
      sorted_students = sorted(students, key=lambda student: student[1])
      
  8. Lambda functions and closures in Python:

    • Description: Explore how lambda functions can be used in creating closures.
    • Code:
      def power_function(x):
          return lambda y: y**x
      
      square = power_function(2)
      cube = power_function(3)
      
  9. Type hints and lambda expressions in Python:

    • Description: Apply type hints when using lambda expressions for better code understanding.
    • Code:
      from typing import Callable
      
      add: Callable[[int, int], int] = lambda x, y: x + y
      result = add(3, 5)