Sometimes you don’t need a full function… just a quick one-liner.
That’s exactly what lambda functions are for.
So far, we’ve learned how to create functions using def.
Those are great for larger tasks.
But in programming, there are moments where you need something very small, very fast, and temporary.
That’s where lambda functions come in.
A lambda function is a short way of writing a function in a single line.
🔹 Basic Lambda Function
Instead of writing a full function like this:
def add(a, b):
return a + b
You can write it using lambda:
add = lambda a, b: a + b
print(add(3, 5))
Same result. Less code.
🔹 How It Works
A lambda function:
- Has no name (or a temporary one)
- Is written in one line
- Is used for simple tasks Structure:
lambda arguments: expression
🔹 Example: Multiply Numbers
multiply = lambda x, y: x * y
print(multiply(4, 6))
🔹 When to Use Lambda
Lambda functions are useful when:
- You need a small function quickly
- You don’t want to define a full function
- You are working with built-in functions like
map()orfilter()(we’ll get there later)
💡 Why Lambda Matters
Lambda functions are not about replacing normal functions.
They are about simplicity.
They help you write cleaner code when the task is small and straightforward.
Think of them as shortcuts not replacements.
🌱 Challenge
Write a lambda function that:
- Takes one number
- Returns the square of that number Then:
- Test it with at least 3 different numbers Try also writing the same thing using a normal function and compare the two.
Next, we’ll explore modules, where you learn how to use code written by other people and organize your own like a real project.
Top comments (0)