Lambda Syntax and Usage
Basic Lambda Syntax
Lambda functions follow a simple and concise syntax:
lambda arguments: expression
Syntax Components
lambda
: Keyword to define an anonymous function
arguments
: Input parameters (zero or more)
expression
: Single line of code to be executed
Single Argument Lambda Functions
## Square a number
square = lambda x: x ** 2
print(square(4)) ## Output: 16
## Convert to uppercase
to_upper = lambda s: s.upper()
print(to_upper("hello")) ## Output: HELLO
Multiple Arguments Lambda Functions
## Addition function
add = lambda x, y: x + y
print(add(3, 5)) ## Output: 8
## Maximum of two numbers
max_num = lambda a, b: a if a > b else b
print(max_num(10, 7)) ## Output: 10
Lambda Function Workflow
graph TD
A[Lambda Keyword] --> B[Arguments]
B --> C[Colon]
C --> D[Single Expression]
D --> E[Immediate Execution/Return]
Common Use Cases
Sorting with Key Function
## Sorting a list of tuples by second element
pairs = [(1, 'one'), (3, 'three'), (2, 'two')]
sorted_pairs = sorted(pairs, key=lambda x: x[1])
print(sorted_pairs) ## Output: [(1, 'one'), (3, 'three'), (2, 'two')]
Filtering Lists
## Filter even numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) ## Output: [2, 4, 6, 8, 10]
Lambda with Built-in Functions
Function |
Lambda Usage |
Example |
map() |
Transform elements |
map(lambda x: x*2, [1,2,3]) |
filter() |
Select elements |
filter(lambda x: x>5, [1,6,3,8]) |
reduce() |
Aggregate values |
reduce(lambda x,y: x+y, [1,2,3,4]) |
Advanced Lambda Techniques
Conditional Expressions
## Ternary-like operation
classify = lambda x: "Positive" if x > 0 else "Non-positive"
print(classify(5)) ## Output: Positive
print(classify(-3)) ## Output: Non-positive
Nested Lambda Functions
## Multiplier generator
def multiplier(n):
return lambda x: x * n
double = multiplier(2)
triple = multiplier(3)
print(double(5)) ## Output: 10
print(triple(5)) ## Output: 15
Best Practices
- Use lambda for simple, one-line operations
- Prefer named functions for complex logic
- Keep lambda functions readable
LabEx recommends practicing these techniques to master lambda functions in Python.