Search This Blog

Lambda Functions in Python

 

Lambda Functions in Python

Lambda functions, also known as anonymous functions or inline functions, are small, simple functions that are defined using the lambda keyword. They are typically used when you need a short function for a specific task and don't want to formally define it using the def keyword.


1. Syntax of a Lambda Function

The basic syntax for a lambda function is as follows:

lambda arguments: expression
  • lambda: The keyword used to define the lambda function.
  • arguments: The parameters that the function will take (just like the parameters in a regular function).
  • expression: A single expression that the function will evaluate and return.

Example 1: Basic Lambda Function

# A lambda function that adds two numbers
add = lambda x, y: x + y

result = add(3, 5)
print(result)  # Output: 8

In this example:

  • lambda x, y: x + y is a function that adds two numbers x and y.
  • The result of add(3, 5) is 8.

2. Lambda Functions with One Argument

You can define a lambda function with just one argument. This is commonly used for operations like squaring a number or doubling a value.

Example 2: Lambda Function with One Argument

# A lambda function that squares a number
square = lambda x: x * x

result = square(4)
print(result)  # Output: 16

In this example, the lambda function takes a single argument x and returns x * x.


3. Lambda Functions with No Arguments

You can also define lambda functions that don't take any arguments. This is useful when the function doesn't need any input but returns a constant value.

Example 3: Lambda Function with No Arguments

# A lambda function that returns a constant value
get_pi = lambda: 3.14159

result = get_pi()
print(result)  # Output: 3.14159

Here, the lambda function returns the constant value 3.14159, which is the approximate value of Pi.


4. Lambda Functions with Conditional Expressions

Lambda functions can include conditional expressions, enabling you to perform if-else logic in a single line.

Example 4: Lambda Function with Conditional Expression

# A lambda function that returns the maximum of two numbers
maximum = lambda x, y: x if x > y else y

result = maximum(10, 20)
print(result)  # Output: 20

In this example:

  • The lambda function checks if x > y, and if true, returns x. Otherwise, it returns y.

5. Using Lambda Functions with Built-in Functions

Lambda functions are often used with Python's built-in functions like map(), filter(), and sorted(). These functions expect a function as an argument and are frequently used with lambda to provide quick, one-off operations.

5.1 Using map() with Lambda

map() applies a function to every item in an iterable (e.g., list) and returns an iterator of the results.

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

# Use lambda to square each number in the list
squared_numbers = map(lambda x: x * x, numbers)

# Convert the result to a list and print
print(list(squared_numbers))  # Output: [1, 4, 9, 16, 25]

In this example:

  • The lambda function lambda x: x * x is used to square each element in the numbers list.

5.2 Using filter() with Lambda

filter() filters elements from an iterable based on a function that returns either True or False. Only elements where the function returns True are kept.

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

# Use lambda to keep only even numbers
even_numbers = filter(lambda x: x % 2 == 0, numbers)

# Convert the result to a list and print
print(list(even_numbers))  # Output: [2, 4, 6]

Here, the lambda function lambda x: x % 2 == 0 checks if a number is even.

5.3 Using sorted() with Lambda

sorted() sorts an iterable. When you need to sort by a specific key, you can use a lambda function as the sorting key.

students = [("Alice", 25), ("Bob", 20), ("Charlie", 30)]

# Sort students by age using a lambda function
sorted_students = sorted(students, key=lambda student: student[1])

print(sorted_students)  # Output: [('Bob', 20), ('Alice', 25), ('Charlie', 30)]

In this example:

  • The lambda function lambda student: student[1] sorts the list by the second element of each tuple (i.e., the age of each student).

6. Advantages and Limitations of Lambda Functions

Advantages:

  • Concise: Lambda functions provide a shorter syntax for writing functions.
  • Inline Usage: You can define simple functions inline without the need for a formal function definition.
  • Functional Programming: Useful when working with functional programming constructs like map(), filter(), and reduce().

Limitations:

  • Single Expression: Lambda functions can only contain a single expression. They cannot have multiple statements or complex logic.
  • Readability: Overuse of lambda functions can lead to less readable code, especially for complex operations.

7. Summary of Lambda Functions

  • Lambda Functions: Anonymous functions defined using the lambda keyword, suitable for short, one-off tasks.
  • Syntax: lambda arguments: expression
  • Use Cases: Often used with functions like map(), filter(), and sorted(), where a simple, small function is needed.
  • Advantages: More concise than regular function definitions and useful in functional programming.
  • Limitations: Can only contain a single expression and may reduce code readability when overused.

Lambda functions are a great tool for simplifying simple operations and for use in higher-order functions. However, for more complex logic, regular functions are often preferred for better readability and maintainability.

Popular Posts