Lambda Expressions
Overview
Lambda expressions are anonymous, single-line functions that can evaluate simple expressions.
Learning Objectives
- Write anonymous inline functions using lambda.
- Use lambdas as sorting criteria keys.
- Understand when to use lambdas and when to use regular functions.
Concept Explanation
A lambda function is a quick, one-line anonymous function. It is declared with the keyword lambda followed by inputs, a colon, and a single expression. Lambdas cannot contain complex statements, loops, or try-except blocks.
Code Examples
Example 1 — Basics
This example introduces the fundamental syntax and concepts.
double = lambda x: x * 2
print(double(5))
Example 2 — Everyday Usage
This example demonstrates a realistic scenario handling business parameters.
# Sort lists of tuples alphabetically by name
students = [(3, 'Charlie'), (1, 'Alice'), (2, 'Bob')]
students.sort(key=lambda s: s[1])
print(students)
Example 3 — Advanced Example
This example shows clean, production-grade code structure following senior development standards.
# Filter logs list using inline conditions
logs = ['INFO: Ingested', 'ERROR: DB Down', 'INFO: Connected']
errors = list(filter(lambda log: 'ERROR' in log, logs))
print(errors)
Visual Flow
The following execution flow represents the step-by-step evaluation inside the interpreter:
Declare Lambda expression → Accept input parameters → Evaluate inline → Return output value
Common Mistakes
Review these common pitfalls when working with this topic:
- Writing complex multi-line logic inside a single lambda.
- Assigning lambdas to variable names instead of using standard def declarations.
- Confusing lambdas with generators or normal scopes.
- Using lambdas in place of simple built-in functions.
Best Practices
Enforce these Pythonic best practices in your codebase:
square = lambda x: x * x # Avoid naming lambdas
def square(x):
return x * x # Clearer debugging stack traces
Quick Revision
Use these key summaries for last-minute revision:
- lambda keyword creates anonymous functions.
- Syntax: lambda arguments: expression.
- Limited to a single expression body.
- Ideal for quick inline key sorting tasks.
- Cannot contain statements or loops.