Lambda Functions
Lambda Functions
Sometimes you need a small function for a quick task.
Instead of writing a full function with def, Python gives a shorter way.
This is called a lambda function.
What Is a Lambda Function?
A lambda function is a small one-line function.
It is useful for simple actions.
Normal Function Example
def double(number):
return number * 2
print(double(5))
Output
10
Same Example with Lambda
double = lambda number: number * 2
print(double(5))
Output
10
How It Works
lambda number: number * 2
Let’s break it down:
lambdastarts the functionnumberis the input value:separates input from resultnumber * 2is the returned result
Why Use Lambda?
Use lambda when:
- The task is short
- You need a quick function
- You do not want a full
defblock
Another Example
add = lambda a, b: a + b
print(add(3, 7))
Output
10
With Sorted Data (Simple Example)
names = ["Tom", "Anna", "Mike"]
names.sort(key=lambda name: len(name))
print(names)
Output
['Tom', 'Mike', 'Anna']
The names are sorted by length.
When Not to Use Lambda
Do not use lambda for large or complex code.
Use normal functions when the logic needs many lines.
Code Along
square = lambda number: number * number
print(square(4))
Output
16
Mini Challenge
Build a quick multiply function.
Steps:
- Create a lambda function called
multiply - It should take two numbers
- Return the answer
- Print the result of
4and5
Expected output:
20
Real World Use Case
Programs use lambda functions for sorting, quick calculations, filtering data, and short helper tasks.
Quiz
- What is a lambda function?
- How many lines is it usually?
- When should you use lambda?
- Which keyword creates a lambda function?
Assignment
Create a lambda function called minus that subtracts two numbers and prints the result.
Summary
You learned that lambda functions are short one-line functions used for simple tasks and quick actions.