- Procedural Programming
- Object-Oriented Programming (OOP)
- Functional Programming
Learning Objectives
After completing this lesson, you will be able to:- Explain the functional programming paradigm.
- Understand the role of higher-order functions.
- Create anonymous functions using
lambda. - Use built-in higher-order functions such as
map(),filter(), andreduce(). - Write programs using a functional programming style.
What is Functional Programming?
Functional programming is a style of programming where functions are the primary building blocks of a program. It is based on two key ideas:- Higher-order functions, which allow functions to be passed and returned like any other object.
- Declarative programming, where we describe what transformation should happen rather than how to perform it step by step.
Note: A declarative programming style alone does not make a language a functional programming language. For example, SQL is declarative because we specify what data we want rather than how to retrieve it. Functional programming combines a declarative style with higher-order functions and function composition.
Procedural Approach
The following program explicitly performs each step.Functional Approach
The same problem can be expressed by composing functions.Characteristics of Functional Programming
- Functions are the primary building blocks.
- Uses higher-order functions extensively.
- Encourages function composition.
- Follows a declarative programming style.
- Focuses on transforming data rather than modifying it.
- Produces modular and reusable code.
Practice
Exercise 1
Which two concepts form the foundation of functional programming?Solution
Solution
Functional programming combines:
- Higher-order functions
- Declarative programming
Exercise 2
What is the main difference between procedural programming and functional programming?Solution
Solution
- Procedural programming focuses on how to perform a task step by step.
- Functional programming focuses on what transformations should be applied by composing functions.
Exercise 3
Is SQL a functional programming language? Why?Solution
Solution
No. SQL follows a declarative programming style, but it is not a functional programming language because it does not use higher-order functions and function composition as its primary programming model.
Python supports functional programming through features such as lambda expressions and built-in higher-order functions likemap(),filter(), andreduce(). We’ll begin by exploring lambda functions in the next section.
Lambda Functions
A lambda function is a small anonymous function created using thelambda keyword. It is commonly used when a function is required for a short period of time and does not need a name.
Lambda functions are frequently used with higher-order functions such as map(), filter(), and sorted().
Syntax
- Can have one or more parameters.
- Contains only a single expression.
- Automatically returns the result of the expression.
- Does not require the
returnkeyword.
Example
A normal function:lambda:
Lambda with Multiple Parameters
Lambda with sorted()
Lambda functions are commonly used to specify a custom sorting rule.
key function returns the second element (marks) of each tuple, so the list is sorted by marks.
When to Use Lambda Functions
Use lambda functions when:- The function is simple.
- It is used only once.
- A higher-order function expects another function as an argument.
- The logic is complex.
- Multiple statements are required.
- The function will be reused in multiple places.
Practice
Exercise 1
Convert the following function into a lambda function.Solution
Solution
Exercise 2
Predict the output.Solution
Solution
Exercise 3
Predict the output.Solution
Solution
key function returns the length of each string, so the list is sorted in ascending order of string length.Exercise 4
When should you prefer a normal function over a lambda function?Solution
Solution
Use a normal function when:
- The logic is complex.
- Multiple statements are required.
- The function will be reused in multiple places.
Lambda functions become especially useful when working with built-in higher-order functions such asmap(),filter(), andreduce(), which we’ll explore next.
Built-in Higher-Order Functions
Python provides several built-in higher-order functions that simplify common data processing tasks. These functions are widely used in functional programming to transform, filter, and combine data. The most commonly used built-in higher-order functions are:map()– Applies a function to every element.filter()– Selects elements that satisfy a condition.reduce()– Combines all elements into a single value.sorted()– Sorts elements using a custom key function.any()– ReturnsTrueif at least one element satisfies a condition.all()– ReturnsTrueonly if all elements satisfy a condition.
The map() Function
The map() function applies a function to every element of an iterable and returns a map object, which is an iterator.
map() returns an iterator, it is commonly converted into a list using the list() function.
Using a Normal Function
Using a Lambda Function
Mapping Multiple Iterables
Practice
Exercise 1
Predict the output.Solution
Solution
1 to each element, and map() applies it to every element in the list.Exercise 2
When should you usemap()?
Solution
Solution
Use
map() when you want to apply the same transformation to every element of an iterable.Some common use cases include:- Squaring numbers
- Converting strings to uppercase
- Calculating percentages
- Formatting data
Whilemap()transforms every element, sometimes we need to select only the elements that satisfy a condition. For this purpose, Python provides thefilter()function.
The filter() Function
The filter() function selects only those elements that satisfy a given condition and returns a filter object, which is an iterator.
filter() should return either True or False.
Since filter() returns an iterator, it is commonly converted into a list using the list() function.
Using a Normal Function
Using a Lambda Function
Another Example
Filter students who scored at least 75 marks.Procedural vs Functional
Procedural ApproachPractice
Exercise 1
Predict the output.Solution
Solution
True only for values greater than 15, so filter() selects only those elements.Exercise 2
Predict the output.Solution
Solution
2.Exercise 3
When should you usefilter()?
Solution
Solution
Use
filter() when you want to select only those elements that satisfy a condition.Some common use cases include:- Selecting even or odd numbers
- Filtering students who passed an exam
- Removing empty strings
- Selecting records based on a condition
The reduce() Function
The reduce() function repeatedly applies a function to the elements of an iterable and combines them into a single value.
Unlike map() and filter(), reduce() is available in the functools module.
Using a Normal Function
Using a Lambda Function
Another Example
Find the product of all numbers.How reduce() Works
Practice
Exercise 1
Predict the output.Solution
Solution
reduce() repeatedly applies the lambda function to combine all elements into a single value.Exercise 2
Predict the output.Solution
Solution
Exercise 3
When should you usereduce()?
Solution
Solution
Use
reduce() when you need to combine all elements of an iterable into a single value, such as calculating the:- Sum
- Product
- Maximum
- Minimum
We have now seen how to transform data usingmap(), filter data usingfilter(), and combine data usingreduce(). Next, we’ll explore other useful built-in higher-order functions such assorted(),any(), andall().
Other Built-in Higher-Order Functions
Besidesmap(), filter(), and reduce(), Python provides several other higher-order functions that are frequently used in functional programming.
The sorted() Function
The sorted() function returns a new sorted list. Using the key parameter, we can specify a function that determines how the elements should be sorted.
Sorting Numbers
Sorting by Length
Sorting Student Records
Practice
Exercise 1
Predict the output.Solution
Solution
reverse=True argument sorts the elements in descending order.Exercise 2
When should you use thekey parameter with the sorted() function?
Solution
Solution
Use the
key parameter when the sorting order should be based on a custom property of each element rather than the element itself.For example:- Sort strings by their length.
- Sort students by their marks.
- Sort dictionaries by a specific key.
The any() Function
The any() function returns True if at least one element in an iterable evaluates to True.
Example
Using any() with a Generator Expression
Practice
Exercise 1
Predict the output.Solution
Solution
False, so any() returns False.The all() Function
The all() function returns True only if every element in an iterable evaluates to True.
Example
Another Example
all() returns False.
Practice
Exercise 1
Predict the output.Solution
Solution
False, the result is False.Exercise 2
What is the difference betweenany() and all()?
Solution
Solution
any()returnsTrueif at least one element satisfies the condition.all()returnsTrueonly if every element satisfies the condition.
Summary of Built-in Higher-Order Functions
These higher-order functions can be combined to build concise and expressive programs. In the next section, we’ll see how to write programs in a functional programming style by composing these functions.
Writing Programs in Functional Style
Functional programming encourages solving problems by composing small functions. Instead of writing step-by-step instructions, we describe the sequence of transformations that should be applied to the data. A common functional programming workflow is:Example 1: Sum of Squares of Even Numbers
Procedural ApproachExample 2: Student Grades
Calculate the average marks of students who scored at least 75 marks.When to Use Functional Programming
Functional programming works well when:- Transforming collections of data.
- Filtering data based on conditions.
- Performing calculations on data.
- Building data processing pipelines.
- Writing reusable functions.
- The logic becomes difficult to read.
- Multiple nested function calls reduce clarity.
- A simple loop is easier to understand.
Readability is more important than writing everything in a functional style.
Real-World Applications
Functional programming concepts are widely used in Python libraries and frameworks, including:- Data processing and analysis
- Machine learning
- ETL pipelines
- Web APIs
- Asynchronous programming
- Background task processing
- Event-driven systems
- Stream processing
Key Takeaways
- Functional programming combines higher-order functions with a declarative programming style.
- Python supports functional programming through lambda expressions and built-in higher-order functions.
map()transforms data.filter()selects data.reduce()combines data into a single value.sorted()performs custom sorting using a key function.any()andall()simplify condition checking.- Functional programming emphasizes composing small functions to build expressive and reusable programs.
Check Your Understanding
Question 1 What are the two main ideas behind functional programming?Solution
Solution
Functional programming combines:
- Higher-order functions
- Declarative programming
Solution
Solution
A lambda function provides a concise way to create a small anonymous function, typically used with higher-order functions.
map()?
Solution
Solution
Use
map() when the same transformation needs to be applied to every element of an iterable.filter()?
Solution
Solution
Use
filter() when selecting elements that satisfy a given condition.reduce()?
Solution
Solution
Use
reduce() when combining all elements of an iterable into a single value.any() and all()?
Solution
Solution
any()returnsTrueif at least one element satisfies the condition.all()returnsTrueonly if every element satisfies the condition.
Solution
Solution
SQL follows a declarative programming style, but it is not a functional programming language because it does not use higher-order functions and function composition as its primary programming model.
Solution
Solution
Functional programming encourages writing modular, reusable, and expressive programs by composing small functions.
Practice & Exercises
To reinforce what you’ve learned in this section (Lambdas, Map, Filter, Reduce, Custom Sorting, any(), and all()), practice with these interactive notebooks:Follow-Along Practice
Practice writing lambda functions, mapping and filtering collections, reducing lists to single values, using custom sorted keys, and checking conditions with any and all.💻 VS Code | 🚀 Colab | 📥 Download
Practice Exercises
Test your skills with exercises on custom lambda sorting of dictionary products, mapping string lengths, filtering vowel-starting words, reducing list elements to products, and validating group scores.💻 VS Code | 🚀 Colab | 📥 Download