Python Functions Tutorial: def, return, Arguments and lambda with Examples
P7.5 Python lambda Functions Explained with Examples
Why. Sometimes you need a tiny function only once — for sorting or for pandas apply. lambda writes it in one line.
What. lambda x: expression is a small function without a name. It can only hold one expression.
How.
Use a lambda
- Write
lambda, the input name, a colon. - Write the expression to return.
- Pass it where a function is expected (like
key=in sorted).
Worked example A — A lambda stored in a variable.
Step 1 — What we do. Convert euros to dollars at 1.08.
Step 2 — Type and run this code.
to_usd = lambda eur: round(eur * 1.08, 2)
print(to_usd(250))
Step 3 — Output you should see.
270.0
Step 4 — What it means. Same as a def with return, just shorter.
Worked example B — Sort records by a field.
Step 1 — What we do. Sort employees of an IT firm by salary.
Step 2 — Type and run this code.
staff = [
{"name": "Kenji", "salary": 72000},
{"name": "Olivia", "salary": 88000},
{"name": "Ravi", "salary": 65000},
]
for s in sorted(staff, key=lambda r: r["salary"], reverse=True):
print(s["name"], s["salary"])
Step 3 — Output you should see.
Olivia 88000
Kenji 72000
Ravi 65000
Step 4 — What it means. key=lambda r: r["salary"] tells sorted what to compare. pandas: df.sort_values("salary").
Python next to other languages — a tiny function. You do not need to learn these other languages. This only shows why Python is easier to read.
| Language | Code |
|---|---|
| Python | lambda x: x * 2 |
| Java | x -> x * 2 |
| JavaScript | x => x * 2 |
| Go | func(x int) int { return x * 2 } |
Ravindra Bagale's Tip
If a lambda does not fit comfortably in one line, use def. Named functions are easier to test.
Ravindra Bagale's Tip – मराठी
Lambda एका line मध्ये आरामात बसत नसेल तर def वापरा. नाव असलेली functions test करायला सोपी.
Ravindra Bagale's Tip – हिंदी
Lambda एक line में आराम से न आए तो def इस्तेमाल करो. नाम वाले functions test करने में आसान.