type
status
date
slug
summary
tags
category
icon
password
What is a
lambda
expression?In Python,
lambda
is used to create anonymous functions. These are temporary, unnamed functions typically used for simple, one-time operations.Basic syntax:
Example:
Equivalent to:
Lambda in RFM analysis:
Explanation:
Calculates recency, the number of days since the last purchase.
Equivalent to:
Calculates frequency, the number of unique invoices.
Equivalent to:
Calculates monetary value, the total amount spent.
Equivalent to:
Lambda vs def:
Feature | lambda | def function |
Has a name? | No | Yes |
Multi-line logic? | No (one expression only) | Yes |
Readability | Lower for complex logic | Better |
Use case | Simple, inline operations | Complex or reusable logic |
Common usage of lambda:
- With
map()
:
Output:
- With
sorted()
:
Output:
- With Pandas
apply()
:
Output:
Limitations of lambda:
- Only one expression is allowed.
- Cannot contain multiple statements.
- Cannot include comments or docstrings.
- Harder to debug and trace in errors.
Summary:
lambda
defines small, anonymous functions.
- Syntax:
lambda args: expression
- Best used for short, simple functions passed as arguments.
- Use
def
when logic is complex or reused.
- Author:Entropyobserver
- URL:https://tangly1024.com/article/1e9d698f-3512-8012-8614-c98e12e37ac5
- Copyright:All articles in this blog, except for special statements, adopt BY-NC-SA agreement. Please indicate the source!