Nearby lessons
73 of 159Python - Lambda Functions
- Understand what a lambda function is and how to create it with the lambda keyword
- Write lambda functions with one, two or three arguments
- Return boolean values and strings from lambda functions
- Compare lambda functions with normal functions
- Use lambda with filter(), map() and reduce()
- Apply lambda functions in practical examples
Introduction to Lambda (Anonymous) Functions
In the previous sections, we learned how to create functions using the def keyword.
Python also provides another way to create functions called Lambda Functions.
A Lambda Function is a small anonymous function that can be created without using the def keyword.
These functions are generally used when a function is required only for a short period of time.
Because they do not have a function name, they are also called Anonymous Functions.
Definition
A Lambda Function is an anonymous function created using the lambda keyword.
It can have any number of parameters but can contain only one expression.
The value of that expression is automatically returned.
Why Do We Need Lambda Functions?
Sometimes we need a function only once in a program.
Creating a complete function using def for such small tasks increases the amount of code.
Lambda Functions provide a simple and compact way to write these small functions.
They are commonly used with built-in functions like:
map()filter()reduce()sorted()
Characteristics of Lambda Functions
- Created using the
lambdakeyword. - Do not have a function name.
- Also called Anonymous Functions.
- Can accept any number of parameters.
- Can contain only one expression.
- Automatically return the result of the expression.
- Generally used for short and simple operations.
Syntax
Syntax Explanation
| Part | Description |
|---|---|
lambda |
Keyword used to create an anonymous function. |
| arguments | Input parameters for the function. |
| expression | The expression whose result is automatically returned. |
First Lambda Function
Explanation
The Lambda Function receives one parameter x.
The expression x * x is evaluated.
The calculated value is automatically returned.
Unlike a normal function, no explicit return statement is required.
Equivalent Normal Function
Comparison
Both functions produce the same output.
The Lambda Function requires fewer lines of code.
It is suitable for simple operations.
Example - Addition
Example - Multiplication
Example - Convert to Uppercase
Lambda Function Flow
| Step | Action |
|---|---|
| 1 | Arguments are passed to the Lambda Function. |
| 2 | The expression is evaluated. |
| 3 | The result is automatically returned. |
Limitations of Lambda Functions
- Can contain only one expression.
- Cannot contain multiple statements.
- Cannot directly use loops like
fororwhile. - Not suitable for writing complex business logic.
- Mainly used for small operations.
Real-World Applications
- Sorting custom objects.
- Data transformation.
- Filtering collections.
- Data analysis.
- Machine Learning preprocessing.
- Using
map(),filter(), andreduce().
Working with Lambda Functions
In the previous section, we learned how to create simple Lambda Functions.
In this section, we will learn how Lambda Functions work with multiple parameters, conditional expressions, and various practical examples.
Since Lambda Functions automatically return the value of a single expression, they are widely used for short calculations.
Lambda Function with Multiple Arguments
A Lambda Function can accept any number of arguments.
All arguments are separated by commas, just like normal function parameters.
Example 1 - Addition
Explanation
The Lambda Function accepts two parameters a and b.
The expression a + b is evaluated and the result is automatically returned.
Example 2 - Multiplication
Example 3 - Find Maximum
Explanation
The Lambda Function uses Python's conditional expression.
If a is greater than b, it returns a; otherwise, it returns b.
Example 4 - Find Minimum
Lambda Function Returning Boolean Values
Lambda Functions can also return Boolean values.
This is useful when checking conditions.
Example 5 - Even Number
Example 6 - Positive Number
Lambda Function with Three Arguments
Lambda Function Returning Strings
Lambda Function with String Operations
Nested Conditional Expression
Flow of Lambda Function
| Step | Description |
|---|---|
| 1 | Arguments are passed to the Lambda Function. |
| 2 | The expression is evaluated. |
| 3 | The result is returned automatically. |
Things to Remember
- Lambda Functions can accept zero, one, or many arguments.
- Only one expression is allowed.
- The expression may contain arithmetic, logical, comparison, or conditional operators.
- The evaluated result is returned automatically.
- Complex business logic should be written using normal functions.
Common Use Cases
- Simple mathematical calculations.
- Conditional expressions.
- Sorting collections.
- Data transformation.
- Filtering records.
- Quick helper functions.
Lambda Function vs Normal Function
Python provides two ways to create functions:
- Normal Functions using the
defkeyword. - Lambda (Anonymous) Functions using the
lambdakeyword.
Both perform the same task of executing reusable code, but they differ in syntax, complexity, and use cases.
Normal Functions are suitable for large programs, whereas Lambda Functions are ideal for short, single-expression operations.
Example 1 - Normal Function
Example 2 - Lambda Function
Explanation
Both functions produce the same output.
The Lambda Function requires fewer lines of code because it automatically returns the expression result.
For simple operations, Lambda Functions make the code shorter and easier to read.
Normal Function vs Lambda Function
| Normal Function | Lambda Function |
|---|---|
Created using the def keyword. |
Created using the lambda keyword. |
| Has a function name. | Usually anonymous (no function name). |
| Can contain multiple statements. | Can contain only one expression. |
Requires an explicit return statement to return a value. |
Automatically returns the expression result. |
| Suitable for large and complex logic. | Suitable for small and simple operations. |
| Supports loops, conditions, exception handling, and multiple statements. | Cannot directly contain loops, multiple statements, or exception handling. |
| Easier to maintain for complex programs. | Useful for quick, temporary helper functions. |
Advantages of Lambda Functions
- Short and concise syntax.
- Requires fewer lines of code.
- No explicit
returnstatement is needed. - Ideal for one-time or temporary functions.
- Works well with built-in functions like
map(),filter(), andreduce(). - Improves readability for simple operations.
- Commonly used in Data Science and Machine Learning code.
Disadvantages of Lambda Functions
- Only one expression is allowed.
- Cannot contain multiple statements.
- Cannot directly use loops such as
forandwhile. - Not suitable for large business logic.
- Can become difficult to read if the expression is too complex.
- Less suitable for debugging than Normal Functions.
When Should You Use Lambda Functions?
Lambda Functions are recommended when:
- A function is required only once.
- The operation is very small.
- Working with
map(),filter(), orreduce(). - Sorting collections using a custom key.
- Writing short callback functions.
When Should You Use Normal Functions?
Normal Functions are recommended when:
- The logic is complex.
- Multiple statements are required.
- The function needs loops or exception handling.
- The function will be reused many times.
- Better readability and maintainability are required.
Real-World Applications of Lambda Functions
- Sorting objects using custom keys.
- Data filtering.
- Data transformation.
- Machine Learning preprocessing.
- Data Analysis with Pandas.
- GUI callback functions.
- Functional programming.
Important Interview Questions
- What is a Lambda Function?
- Why is a Lambda Function called an Anonymous Function?
- What is the syntax of a Lambda Function?
- How many expressions are allowed inside a Lambda Function?
- Can Lambda Functions have multiple parameters?
- Differentiate between Normal Functions and Lambda Functions.
- What are the advantages of Lambda Functions?
- What are the disadvantages of Lambda Functions?
- Where are Lambda Functions commonly used?
- Why are Lambda Functions frequently used with
map(),filter(), andreduce()?
Introduction to filter() Function
The filter() function is one of Python's built-in functions.
It is used to select elements from an iterable (such as a list, tuple, or set) based on a given condition.
Instead of modifying the original collection, filter() creates a new iterator that contains only the elements that satisfy the specified condition.
In Python, filter() is commonly used together with Lambda Functions to write short and efficient code.
Definition
The filter() function filters elements from an iterable by applying a function to each element.
If the function returns True, the element is included in the result.
If the function returns False, the element is discarded.
Why Do We Need filter()?
Suppose we have a list containing hundreds of numbers.
If we want only the even numbers, we would normally use a loop with an if statement.
The filter() function performs this task in a much shorter and cleaner way.
It helps improve code readability and reduces the amount of code.
Syntax
Syntax Explanation
| Parameter | Description |
|---|---|
function |
A function that returns either True or False. |
iterable |
The collection whose elements will be filtered. |
Return Value
The filter() function returns a filter object.
This filter object is an iterator.
To display the filtered values, it is usually converted into a list, tuple, or set.
Program 1 - Simple filter() Example
Explanation
The Lambda Function checks whether each number is greater than 20.
If the condition is True, the element is selected.
Initially, filter() returns a filter object.
After converting it into a list using list(), the filtered values become visible.
Program 2 - Filtering Even Numbers
Explanation
The Lambda Function checks whether the remainder after dividing by 2 is equal to 0.
If the condition is true, the number is included in the result.
Program 3 - Filtering Odd Numbers
Program 4 - Using a Normal Function
Explanation
Instead of using a Lambda Function, a Normal Function can also be passed to filter().
The function should always return True or False.
How filter() Works
| Element | Condition | Included? |
|---|---|---|
| 10 | True | ✔ Yes |
| 15 | False | ✘ No |
| 20 | True | ✔ Yes |
| 25 | False | ✘ No |
| 30 | True | ✔ Yes |
Flow of filter() Function
| Step | Description |
|---|---|
| 1 | Read one element from the iterable. |
| 2 | Pass the element to the function. |
| 3 | If the function returns True, keep the element. |
| 4 | If the function returns False, discard the element. |
| 5 | Return the filtered iterator. |
More filter() Examples
In the previous section, we learned the basics of the filter() function.
In this section, we will explore more practical examples using different types of data.
These examples demonstrate how filter() can be used to filter numbers, strings, and other collections efficiently.
Program 1 - Filter Positive Numbers
Explanation
The Lambda Function checks whether each number is greater than 0.
Only positive numbers satisfy the condition and are included in the result.
Program 2 - Filter Negative Numbers
Program 3 - Filter Numbers Greater Than 50
Program 4 - Filter Numbers Divisible by 5
Program 5 - Filter Non-Empty Strings
Explanation
The Lambda Function checks whether the string is not empty.
Only non-empty strings are included in the final result.
Program 6 - Filter Names Starting with 'A'
Program 7 - Filter String Length Greater Than 5
Program 8 - Filter Even Numbers from a Tuple
Program 9 - Filter Values from a Set
Program 10 - Using filter() with None
Explanation
When None is passed as the first argument, filter() automatically removes all falsy values.
Falsy values include:
0FalseNone- Empty String (
"") - Empty List
- Empty Tuple
- Empty Dictionary
Only truthy values remain in the final output.
Real-World Applications
- Filtering active users from a database.
- Selecting students who passed an examination.
- Removing invalid records from datasets.
- Filtering positive transactions.
- Cleaning missing values during data preprocessing.
- Filtering API response data.
- Filtering files based on extensions.
Advantages of filter()
- Produces clean and readable code.
- Reduces the need for manual loops.
- Works efficiently with Lambda Functions.
- Supports all iterable objects.
- Returns an iterator, making it memory efficient.
- Useful for data filtering tasks.
Important Interview Questions
- What is the purpose of the
filter()function? - What does
filter()return? - Why is
list()commonly used withfilter()? - Can
filter()work with Normal Functions? - Can
filter()work with Lambda Functions? - What happens when
Noneis passed tofilter()? - Which iterable objects are supported by
filter()? - Differentiate between
filter()and loops.
Introduction to map() Function
The map() function is one of Python's built-in functions.
It is used to apply a function to every element of an iterable such as a list, tuple, set, or string.
Unlike filter(), which selects elements based on a condition, map() transforms every element and returns the modified values.
The original iterable remains unchanged because map() creates a new iterator containing the transformed elements.
In Python, map() is commonly used together with Lambda Functions to write concise and efficient code.
Definition
The map() function applies a specified function to each element of an iterable.
The transformed elements are returned as a map object.
Why Do We Need map()?
Suppose we have a list of numbers and want to calculate the square of every number.
Normally, we would use a loop and create another list.
The map() function performs this task in a cleaner and shorter way.
It reduces the amount of code and improves readability.
Syntax
Syntax Explanation
| Parameter | Description |
|---|---|
function |
The function that will be applied to every element. |
iterable |
The collection whose elements will be transformed. |
Return Value
The map() function returns a map object.
The map object is an iterator.
To display the transformed values, it is generally converted into a list, tuple, or set.
Program 1 - First map() Example
Explanation
The Lambda Function multiplies every number by 2.
Initially, map() returns a map object.
Using list(), the transformed values become visible.
Program 2 - Square of Numbers
Program 3 - Cube of Numbers
Program 4 - Using a Normal Function
Explanation
Instead of using a Lambda Function, a Normal Function can also be passed to map().
The function is applied to every element of the iterable one by one.
Program 5 - Convert Strings to Uppercase
Program 6 - Find Length of Strings
How map() Works
| Original Element | Transformation | New Value |
|---|---|---|
| 1 | x × 2 | 2 |
| 2 | x × 2 | 4 |
| 3 | x × 2 | 6 |
| 4 | x × 2 | 8 |
| 5 | x × 2 | 10 |
Flow of map() Function
| Step | Description |
|---|---|
| 1 | Read one element from the iterable. |
| 2 | Pass the element to the function. |
| 3 | Transform the element. |
| 4 | Store the transformed value. |
| 5 | Return a map object. |
More map() Examples
In the previous section, we learned the basics of the map() function.
In this section, we will explore more practical examples using numbers, strings, and multiple iterables.
These examples demonstrate how map() can efficiently transform data without modifying the original iterable.
Program 1 - Add 10 to Every Number
Explanation
The Lambda Function adds 10 to every element.
The transformed values are returned as a new iterator.
Program 2 - Convert Strings to Lowercase
Program 3 - Capitalize First Letter
Program 4 - Convert Integers to Strings
Explanation
The built-in str() function is passed directly to map().
Each integer is converted into its string representation.
Program 5 - Find Length of Each String
Program 6 - Square of Tuple Elements
Program 7 - Multiply Elements from Two Lists
Explanation
map() can accept multiple iterables.
The Lambda Function receives one element from each iterable at the same position.
The corresponding elements are multiplied together.
Program 8 - Add Elements of Two Lists
Program 9 - Convert List of Strings to Integers
Program 10 - Remove Extra Spaces
Working with Multiple Iterables
One of the important features of map() is that it can process multiple iterables simultaneously.
The supplied function receives one value from each iterable during every iteration.
If the iterables have different lengths, processing stops when the shortest iterable is exhausted.
Flow of map() with Multiple Iterables
| List 1 | List 2 | Lambda Result |
|---|---|---|
| 1 | 10 | 10 |
| 2 | 20 | 40 |
| 3 | 30 | 90 |
| 4 | 40 | 160 |
Real-World Applications
- Converting data types.
- Formatting user input.
- Cleaning datasets before analysis.
- Performing mathematical calculations.
- Transforming API response data.
- Data preprocessing for Machine Learning.
- Applying the same operation to every record.
Advantages of map()
- Produces concise and readable code.
- Eliminates manual loops.
- Works efficiently with Lambda Functions.
- Supports multiple iterables.
- Returns an iterator, making it memory efficient.
- Does not modify the original iterable.
Important Interview Questions
- What is the purpose of the
map()function? - What does
map()return? - Can
map()work with Normal Functions? - Can
map()process multiple iterables? - What happens if multiple iterables have different lengths?
- How is
map()different fromfilter()? - Can built-in functions like
str()andlen()be passed tomap()? - Why is
map()widely used in Data Science?
Introduction to reduce() Function
The reduce() function is used to reduce an entire iterable into a single value.
Unlike map(), which transforms every element, and filter(), which selects specific elements, reduce() repeatedly combines the elements of an iterable until only one final result remains.
The reduce() function is not a built-in function in Python 3.
It is available inside the functools module.
Definition
The reduce() function repeatedly applies a specified function to the elements of an iterable and produces a single final value.
Each iteration combines two values into one until all elements have been processed.
Why Do We Need reduce()?
Suppose we have a list of numbers.
If we want to calculate the total sum or product of all numbers, we normally use a loop.
The reduce() function performs this operation with very little code.
It is especially useful for cumulative calculations.
Importing reduce()
Explanation
Since Python 3, reduce() belongs to the functools module.
Therefore, it must be imported before it can be used.
Syntax
Syntax Explanation
| Parameter | Description |
|---|---|
function |
Function that combines two values. |
iterable |
Collection whose values are processed. |
initializer |
Optional starting value for the reduction. |
Return Value
The reduce() function returns a single value.
This value is the final result after processing all elements of the iterable.
Program 1 - First reduce() Example
Explanation
The Lambda Function adds two values together.
The first two elements are added, then the result is added to the next element.
This process continues until every element has been processed.
The final result is 100.
Step-by-Step Execution
Program 2 - Product of Numbers
Step-by-Step Execution
Program 3 - Using a Normal Function
Explanation
Instead of using a Lambda Function, a Normal Function can also be supplied to reduce().
The function always receives two arguments.
The returned value becomes the first argument for the next iteration.
Program 4 - Using an Initializer
Explanation
The initializer provides the starting value.
The reduction begins with 100.
Calculation:
100 + 10 = 110
110 + 20 = 130
130 + 30 = 160
How reduce() Works
| Iteration | Current Values | Result |
|---|---|---|
| 1 | 10, 20 | 30 |
| 2 | 30, 30 | 60 |
| 3 | 60, 40 | 100 |
Flow of reduce() Function
| Step | Description |
|---|---|
| 1 | Take the first two elements. |
| 2 | Apply the supplied function. |
| 3 | Store the returned result. |
| 4 | Combine the result with the next element. |
| 5 | Repeat until all elements are processed. |
| 6 | Return one final value. |
More reduce() Examples
In the previous section, we learned the basics of the reduce() function.
In this section, we will solve more practical examples using reduce().
These examples demonstrate how multiple values are repeatedly combined into a single final result.
Program 1 - Find Sum of Numbers
Explanation
The Lambda Function adds two numbers at a time.
The intermediate result becomes the first argument for the next iteration until a single final value remains.
Step-by-Step Execution
Program 2 - Find Product of Numbers
Step-by-Step Execution
Program 3 - Find Maximum Number
Explanation
The Lambda Function compares two values.
The larger value is carried forward to the next comparison.
Finally, the largest value is returned.
Program 4 - Find Minimum Number
Program 5 - Concatenate Strings
Program 6 - Find Longest String
Program 7 - Sum with Initializer
Explanation
The reduction starts with the initializer value 100.
Then every element of the iterable is added one by one.
Program 8 - Product with Initializer
Step-by-Step Execution
Real-World Applications of reduce()
- Finding the total sales amount.
- Calculating total marks.
- Finding maximum and minimum values.
- Computing products of numbers.
- String concatenation.
- Financial calculations.
- Data aggregation in Data Science.
- Machine Learning preprocessing.
Advantages of reduce()
- Produces short and readable code.
- Ideal for cumulative calculations.
- Works efficiently with Lambda Functions.
- Returns a single final value.
- Supports an optional initializer.
- Useful in Functional Programming.
Comparison - filter(), map(), reduce()
| Function | Purpose | Returns |
|---|---|---|
filter() |
Select elements based on a condition. | Filter Object |
map() |
Transform every element. | Map Object |
reduce() |
Combine all elements into one value. | Single Value |
Important Interview Questions
- What is the purpose of
reduce()? - Which module contains the
reduce()function? - What does
reduce()return? - How many arguments does the supplied function receive?
- What is the purpose of the initializer?
- Can Normal Functions be used with
reduce()? - Differentiate between
filter(),map(), andreduce(). - Where is
reduce()commonly used in real-world applications?
Introduction
Python provides three powerful functional programming utilities:
filter()map()reduce()
These functions are commonly used together with Lambda Functions to write short, readable, and efficient code.
Although all three functions work with iterables, each one serves a different purpose.
Quick Overview
| Function | Main Purpose |
|---|---|
filter() |
Select elements that satisfy a condition. |
map() |
Transform every element. |
reduce() |
Combine all elements into a single value. |
Comparison - filter() vs map() vs reduce()
| Feature | filter() | map() | reduce() |
|---|---|---|---|
| Purpose | Select elements | Transform elements | Combine elements |
| Input | Function + Iterable | Function + One or More Iterables | Function + Iterable |
| Output | Filter Object | Map Object | Single Value |
| Works with Lambda | Yes | Yes | Yes |
| Works with Normal Function | Yes | Yes | Yes |
| Returns Iterator | Yes | Yes | No |
| Returns Single Value | No | No | Yes |
| Memory Efficient | Yes | Yes | Yes |
| Main Use | Filtering Data | Data Transformation | Aggregation |
When Should You Use Each Function?
| Situation | Recommended Function |
|---|---|
| Select even numbers | filter() |
| Select students who passed | filter() |
| Convert names to uppercase | map() |
| Calculate square of every number | map() |
| Find total marks | reduce() |
| Find product of numbers | reduce() |
| Find largest value | reduce() |
Advantages
filter()
- Selects only required elements.
- Produces cleaner code.
- Memory efficient.
map()
- Transforms every element.
- Reduces manual loops.
- Supports multiple iterables.
reduce()
- Produces one final result.
- Ideal for aggregation.
- Useful for mathematical calculations.
Disadvantages
| Function | Disadvantages |
|---|---|
filter() |
Only selects elements; cannot transform them. |
map() |
Cannot directly filter unwanted elements. |
reduce() |
May reduce readability for beginners when used with complex expressions. |
Real-World Applications
| Application | Function Used |
|---|---|
| Filter active users | filter() |
| Remove invalid records | filter() |
| Convert currencies | map() |
| Convert temperatures | map() |
| Total sales calculation | reduce() |
| Payroll calculation | reduce() |
| Data preprocessing | All Three |
| Machine Learning | All Three |
Important Interview Questions
- Differentiate between
filter(),map(), andreduce(). - What does each function return?
- Which module contains
reduce()? - Can all three functions work with Lambda Functions?
- Can all three functions work with Normal Functions?
- Which function returns a single value?
- Which function supports multiple iterables?
- When should
filter()be preferred overmap()? - Explain a real-world use case for each function.
- What are the advantages of Functional Programming in Python?
- A lambda function is a small anonymous function created with the lambda keyword
- A lambda can have any number of parameters but only one expression
- The value of the lambda expression is automatically returned
- lambda is commonly used with filter(), map() and reduce()
- Lambda functions are concise but limited compared to normal functions