Lambda Functions
Learn how to write small, anonymous functions in a single line
Learning Objectives
- Understand what an anonymous function is
- Write basic 'lambda' functions
- Learn when to use lambda vs. regular functions
Anonymous Functions
Sometimes you need a small function for a short period of time, and you don’t even want to give it a name using def. These are called Anonymous Functions, and in Python, we create them using the lambda keyword.
The Lambda Syntax
The syntax for a lambda function is:
lambda arguments : expression
|
|
Characteristics:
- It can take any number of arguments.
- It can only have one expression.
- It automatically returns the result of that expression.
Why use Lambda?
Lambdas are most useful when passed as an argument to another function.
Example: Custom Sorting
Imagine you have a list of tuples representing students and their scores, and you want to sort them by score.
|
|
Lambda vs. Def
| Feature | def |
lambda |
|---|---|---|
| Name | Required | Anonymous |
| Body | Multiple lines | Single expression |
| Use Case | Complex logic | Simple, one-time tasks |
| Reusability | High | Low |
def function. Code is read more often than it is written!Interactive Practice
Try writing a lambda function that takes one number and returns its square (number multiplied by itself).
Quiz
Complete this quiz with a minimum score of 80% to mark Day 10 as complete.
Discussion
Have questions or want to discuss this lesson? Join the conversation below!