Functional Programming
Functional programming is a programming paradigm where functions are treated as first-class objects. Python provides several functional programming features that help write concise, reusable, and expressive code.Topics Covered
In this module, you’ll learn:- Functions as Objects
- Functions as First-Class Objects
- Passing Functions as Arguments
- Returning Functions
- Higher-Order Functions
- Anonymous (Lambda) Functions
map()filter()reduce()- Functional Programming Best Practices
Try Yourself: 💻 VS Code | 🚀 Colab | 📥 DownloadBy the end of this module, you’ll be able to treat functions as data, write reusable higher-order functions, use lambda expressions effectively, and apply Python’s built-in functional programming utilities.
Verify Solutions: 💻 VS Code | 🚀 Colab | 📥 Download
Functions as Objects
In Python, everything is an object, including functions. This means a function can be:- Assigned to a variable
- Passed as an argument
- Returned from another function
- Stored in a collection
Show Output
Show Output
message.
Function References
Both variables refer to the same function object.Show Output
Show Output
is operator confirms that both variables reference the same function object.
Exercise 1
Assign a function namedwelcome() to another variable and invoke it.
Sample Input
Solution
Solution
Exercise 2
Create a function nameddisplay() and assign it to another variable named show. Invoke both variables.
Sample Input
Solution
Solution
Functions as First-Class Objects
A programming language is said to support first-class functions if functions can be treated just like any other object. Since Python functions are objects, they can:- Be assigned to variables
- Be stored in collections
- Be passed as arguments
- Be returned from functions
Show Output
Show Output
Show Output
Show Output
Exercise 1
Store two functions in a list and invoke each function. Sample InputSolution
Solution
Exercise 2
Store functions inside a dictionary and invoke them using keys. Sample InputSolution
Solution
Passing Functions as Arguments
Since functions are objects, they can be passed as arguments to other functions.Show Output
Show Output
Exercise 1
Create a functionwelcome() and pass it to another function named run().
Sample Input
Solution
Solution
Exercise 2
Create two greeting functions and execute each by passing it to another function. Sample InputSolution
Solution
Returning Functions
Functions can also return other functions.Show Output
Show Output
Exercise 1
Create a function that returns another function displaying"Python".
Sample Input
Solution
Solution
Exercise 2
Create a function that returns another function displaying"Functional Programming".
Sample Input
Solution
Solution
Higher-Order Functions
A higher-order function is a function that does at least one of the following:- Accepts one or more functions as arguments.
- Returns a function.
Accepting a Function as an Argument
Show Output
Show Output
execute() is a higher-order function because it accepts another function as an argument.
Returning a Function
A higher-order function can also return another function.Show Output
Show Output
Why Higher-Order Functions?
Higher-order functions help:- Eliminate duplicate code.
- Improve code reusability.
- Separate behavior from implementation.
- Build flexible and extensible programs.
Exercise 1
Create a higher-order function that accepts a function and executes it. Sample InputSolution
Solution
Exercise 2
Create a higher-order function that returns a function displaying"Welcome".
Sample Input
Solution
Solution
Anonymous (Lambda) Functions
Sometimes a function is needed only once. Instead of defining a function usingdef, Python provides lambda functions, also known as anonymous functions.
Using a Regular Function
Show Output
Show Output
Using a Lambda Function
Show Output
Show Output
- Can have any number of parameters.
- Contains only one expression.
- Automatically returns the result of the expression.
Multiple Parameters
Show Output
Show Output
Using Conditional Expressions
Show Output
Show Output
When Should You Use Lambda Functions?
Lambda functions are useful when:- The function is short.
- The function is used only once.
- Passing functions to
map(),filter(), orsorted().
def.
Exercise 1
Create a lambda function that returns the cube of a number. Sample InputSolution
Solution
Exercise 2
Create a lambda function that returns the smaller of two numbers. Sample InputSolution
Solution
Lambda Functions with Built-in Functions
Lambda functions become particularly useful when combined with Python’s built-in functional programming functions. The three most commonly used functions are:map()filter()reduce()
Higher-Order Functions
A higher-order function is a function that either:- Accepts one or more functions as arguments.
- Returns a function.
Passing Functions as Arguments
Show Output
Show Output
notify() function is a higher-order function because it accepts another function as an argument.
Returning Functions
Show Output
Show Output
Exercise 1
Create a higher-order function that accepts a greeting function and a person’s name. Sample InputSolution
Solution
Exercise 2
Create a function that returns another function to calculate a discount. Sample InputSolution
Solution
Anonymous (Lambda) Functions
A lambda function is a small anonymous function consisting of a single expression. Instead of writingShow Output
Show Output
Multiple Parameters
Show Output
Show Output
Conditional Expression
Show Output
Show Output
When Should You Use Lambda Functions?
Use lambda functions when:- The function is small.
- It is used only once.
- It is passed to another function such as
map(),filter(), orsorted().
Exercise 1
Create a lambda function that calculates the area of a rectangle. Sample InputSolution
Solution
Exercise 2
Create a lambda function that returns"Eligible" if age is at least 18; otherwise, return "Not Eligible".
Sample Input
Solution
Solution
The map() Function
The map() function applies a function to every element of an iterable and returns an iterator.
Traditional Approach
Suppose we want to apply a 10% discount to all product prices.Show Output
Show Output
Using map()
Show Output
Show Output
Another Example
Convert employee names to uppercase.Show Output
Show Output
Exercise 1
Convert all city names to title case. Sample InputSolution
Solution
Exercise 2
Add 18% GST to every product price. Sample InputSolution
Solution
The filter() Function
The filter() function selects only those elements that satisfy a condition.
Traditional Approach
Suppose we want to display only students who passed.Show Output
Show Output
Using filter()
Show Output
Show Output
Another Example
Filter premium products costing more than ₹1000.Show Output
Show Output
Exercise 1
Filter employees earning more than ₹50,000. Sample InputSolution
Solution
Exercise 2
Filter words having more than five characters. Sample InputSolution
Solution
The reduce() Function
The reduce() function repeatedly applies a function to the elements of an iterable and reduces them to a single value.
Unlike map() and filter(), which return iterators, reduce() produces a single result.
The reduce() function is available in the functools module.
Traditional Approach
Suppose we want to calculate the total amount of items in a shopping cart.Show Output
Show Output
Using reduce()
Show Output
Show Output
Another Example
Find the highest employee salary.Show Output
Show Output
Exercise 1
Calculate the total quantity of products sold. Sample InputSolution
Solution
Exercise 2
Find the minimum salary. Sample InputSolution
Solution
Combining map(), filter(), and reduce()
In real-world applications, these functions are often combined to process data in multiple stages.
Suppose a company wants to:
- Increase every employee’s salary by 10%.
- Consider only employees earning more than ₹50,000 after the increment.
- Calculate the total payroll of those employees.
Show Output
Show Output
Processing Pipeline
map()transforms every element.filter()selects only the required elements.reduce()combines all elements into a single result.
Comprehensive Exercise 1
Given the marks of students,- Add 5 grace marks to every student.
- Keep only students scoring 40 or above.
- Calculate the total marks.
Solution
Solution
Comprehensive Exercise 2
Given the prices of products,- Apply a 10% discount to every product.
- Keep only products costing more than ₹1000 after the discount.
- Calculate the final bill.
Solution
Solution
Comprehensive Exercise 3
Given the employee names,- Convert all names to uppercase.
- Keep only names having more than 5 characters.
- Join them into a comma-separated string.
Solution
Solution
Choosing the Right Function
Functional Programming Best Practices
- Use regular functions (
def) for complex logic. - Use lambda functions for short, simple operations.
- Use
map()to transform every element. - Use
filter()to select elements based on a condition. - Use
reduce()to aggregate values into a single result. - Prefer list comprehensions over
map()andfilter()for simple transformations when they improve readability. - Choose the approach that makes your code easiest to read and maintain.
Note: In modern Python, list comprehensions are often preferred overmap()andfilter()for simple transformations because they are generally more readable. However,map(),filter(), andreduce()remain valuable tools when building functional pipelines or working with existing functions.
Practice
To reinforce what you’ve learned in this section, practice with the interactive follow-along notebook:Follow-Along Practice
Summary
In this module, you learned how Python supports functional programming by treating functions as first-class objects.Key Concepts Covered
- Functions as Objects
- Functions as First-Class Objects
- Passing Functions as Arguments
- Returning Functions
- Higher-Order Functions
- Anonymous (Lambda) Functions
map()filter()reduce()- Combining
map(),filter(), andreduce() - Functional Programming Best Practices