Skip to main content

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:
  1. Functions as Objects
  2. Functions as First-Class Objects
  3. Passing Functions as Arguments
  4. Returning Functions
  5. Higher-Order Functions
  6. Anonymous (Lambda) Functions
  7. map()
  8. filter()
  9. reduce()
  10. Functional Programming Best Practices
Try Yourself: 💻 VS Code | 🚀 Colab | 📥 Download
Verify Solutions: 💻 VS Code | 🚀 Colab | 📥 Download
By 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.

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
Let’s begin by assigning a function to another variable.
Output ?
Notice that we assigned the function itself, not its return value.
If we write
the function executes immediately and the return value is assigned to message.

Function References

Both variables refer to the same function object.
Output ?
The is operator confirms that both variables reference the same function object.

Exercise 1

Assign a function named welcome() to another variable and invoke it. Sample Input
Expected Output

Exercise 2

Create a function named display() and assign it to another variable named show. Invoke both variables. Sample Input
Expected Output

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
For example, functions can even be stored inside a list.
Output ?
Functions can also be stored in dictionaries.
Output ?

Exercise 1

Store two functions in a list and invoke each function. Sample Input
Expected Output

Exercise 2

Store functions inside a dictionary and invoke them using keys. Sample Input
Expected Output

Passing Functions as Arguments

Since functions are objects, they can be passed as arguments to other functions.
Output ?
Notice that we pass the function without parentheses.
If we write
the function executes first, and its return value is passed instead. Passing functions as arguments makes code more flexible and reusable.

Exercise 1

Create a function welcome() and pass it to another function named run(). Sample Input
Expected Output

Exercise 2

Create two greeting functions and execute each by passing it to another function. Sample Input
Expected Output

Returning Functions

Functions can also return other functions.
Output ?
The returned function can be stored in a variable and executed later. This capability forms the foundation for higher-order functions, closures, and decorators.

Exercise 1

Create a function that returns another function displaying "Python". Sample Input
Expected Output

Exercise 2

Create a function that returns another function displaying "Functional Programming". Sample Input
Expected Output

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.
Since Python functions are first-class objects, creating higher-order functions is straightforward.

Accepting a Function as an Argument

Output ?
Here, 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.
Output ?

Why Higher-Order Functions?

Higher-order functions help:
  • Eliminate duplicate code.
  • Improve code reusability.
  • Separate behavior from implementation.
  • Build flexible and extensible programs.
They are widely used in Python libraries and frameworks.

Exercise 1

Create a higher-order function that accepts a function and executes it. Sample Input
Expected Output

Exercise 2

Create a higher-order function that returns a function displaying "Welcome". Sample Input
Expected Output

Anonymous (Lambda) Functions

Sometimes a function is needed only once. Instead of defining a function using def, Python provides lambda functions, also known as anonymous functions.

Using a Regular Function

Output ?

Using a Lambda Function

Output ?
The general syntax is:
A lambda function:
  • Can have any number of parameters.
  • Contains only one expression.
  • Automatically returns the result of the expression.

Multiple Parameters

Output ?

Using Conditional Expressions

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(), or sorted().
For complex logic, prefer a normal function using def.

Exercise 1

Create a lambda function that returns the cube of a number. Sample Input
Expected Output

Exercise 2

Create a lambda function that returns the smaller of two numbers. Sample Input
Expected Output

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()
These functions allow data to be transformed, filtered, and aggregated without writing explicit loops. In the following sections, you’ll learn how each of these functions works and when to use them.

Higher-Order Functions

A higher-order function is a function that either:
  • Accepts one or more functions as arguments.
  • Returns a function.
Higher-order functions make code more flexible and reusable by separating behavior from implementation.

Passing Functions as Arguments

Output ?
The notify() function is a higher-order function because it accepts another function as an argument.

Returning Functions

Output ?
Higher-order functions are widely used in web frameworks, event handling, decorators, and callback functions.

Exercise 1

Create a higher-order function that accepts a greeting function and a person’s name. Sample Input
Expected Output

Exercise 2

Create a function that returns another function to calculate a discount. Sample Input
Expected Output

Anonymous (Lambda) Functions

A lambda function is a small anonymous function consisting of a single expression. Instead of writing
we can write
Output ?

Multiple Parameters

Output ?

Conditional Expression

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(), or sorted().
For complex logic, prefer a regular function.

Exercise 1

Create a lambda function that calculates the area of a rectangle. Sample Input
Expected Output

Exercise 2

Create a lambda function that returns "Eligible" if age is at least 18; otherwise, return "Not Eligible". Sample Input
Expected Output

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.
Output ?

Using map()

Output ?

Another Example

Convert employee names to uppercase.
Output ?

Exercise 1

Convert all city names to title case. Sample Input
Expected Output

Exercise 2

Add 18% GST to every product price. Sample Input
Expected Output

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.
Output ?

Using filter()

Output ?

Another Example

Filter premium products costing more than ₹1000.
Output ?

Exercise 1

Filter employees earning more than ₹50,000. Sample Input
Expected Output

Exercise 2

Filter words having more than five characters. Sample Input
Expected Output

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.
Output ?

Using reduce()

Output ?

Another Example

Find the highest employee salary.
Output ?

Exercise 1

Calculate the total quantity of products sold. Sample Input
Expected Output

Exercise 2

Find the minimum salary. Sample Input
Expected Output

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:
  1. Increase every employee’s salary by 10%.
  2. Consider only employees earning more than ₹50,000 after the increment.
  3. Calculate the total payroll of those employees.
Output ?

Processing Pipeline

Each function performs a specific task:
  • 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,
Perform the following operations:
  1. Add 5 grace marks to every student.
  2. Keep only students scoring 40 or above.
  3. Calculate the total marks.
Expected Output

Comprehensive Exercise 2

Given the prices of products,
Perform the following operations:
  1. Apply a 10% discount to every product.
  2. Keep only products costing more than ₹1000 after the discount.
  3. Calculate the final bill.
Expected Output

Comprehensive Exercise 3

Given the employee names,
Perform the following operations:
  1. Convert all names to uppercase.
  2. Keep only names having more than 5 characters.
  3. Join them into a comma-separated string.
Expected Output

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() and filter() 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 over map() and filter() for simple transformations because they are generally more readable. However, map(), filter(), and reduce() 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

Practice first-class functions, higher-order functions, lambda expressions, map, filter, and reduce operations.💻 VS Code | 🚀 Colab | 📥 Download

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(), and reduce()
  • Functional Programming Best Practices
Functional programming encourages writing reusable, expressive, and modular code. By combining higher-order functions, lambda expressions, and Python’s built-in functional programming utilities, you can solve data-processing problems in a clean, concise, and maintainable way.