
👉Python Lambda Functions with Examples
Python Lambda Functions: A Lambda Function in Python is an anonymous function that doesn’t have a defined name. These are simple, one-line functions often used for short operations.
👉What is a Lambda Function in Python?
Python Lambda Functions : A Lambda function is defined using the lambda keyword, followed by parameters and a single expression. Unlike regular functions, lambda functions are concise and designed for quick tasks.
👉Syntax:
lambda parameters: expression
👉Example 1: Basic Lambda Function
adder = lambda x, y: x + y
print(adder(3, 5))
👉Output:
8
👉Example 2: Lambda with Immediate Execution (IIFE)
print((lambda x: x * 2)(4))
👉Output:
8
👉Example 3: Lambda with Built-in Functions
Python’s built-in functions like map(), filter(), and reduce() work seamlessly with lambda functions.
👉Using lambda with filter()
numbers = [1, 2, 3, 4, 5, 6]
filtered_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(filtered_numbers))
👉Output:
[2, 4, 6]
👉Using lambda with map()
numbers = [1, 2, 3, 4]
squared_numbers = map(lambda x: x ** 2, numbers)
print(list(squared_numbers))
👉Output:
[1, 4, 9, 16]
👉Using lambda with reduce()
from functools import reduce
numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product)
👉Output:
24
👉When to Use Lambda Functions
- Ideal for short, concise operations.
- Useful in functional programming with functions like map(), filter(), and reduce().
- Great for simple expressions where writing a full function is unnecessary.
👉When to Avoid Lambda Functions
- Avoid complex logic inside lambda functions.
- When code readability and maintainability are priorities, use regular functions instead.
👉Lambda vs. Regular Functions
Feature | Lambda Functions | Regular Functions |
Syntax | lambda x: x * 2 | def multiply(x): return x * 2 |
Multiple Statements | Not possible | Possible |
Return Statement | Implicit | Explicit |