Table of contents
Functional programming is a programming prototype that emphasizes the use of functions that take inputs and produce outputs without altering the state of the program. Python supports functional programming features such as lambda functions, map, filter, and reduce functions, which allow for a more declarative and expressive style of coding.
PermalinkLambda Functions
Lambda functions, also known as anonymous functions, are small, inline functions defined using the lambda
keyword. They are useful for writing short, one-line functions without explicitly defining a function using def
. Lambda functions can take any number of arguments but can only have a single expression.
lambda arguments: expression
arguments
: input parameters or variables that the lambda function takes.expression
: Single expression or operation to be evaluated and returned as the result of the lambda function.
PermalinkMap Function
The map()
function in Python is a built-in function that applies a specified function to each item of an iterable and returns a new iterable containing the results. It allows you to transform each element of the original iterable according to the provided function.
map(function, iterable)
Let's see an example where we use lambda functions with the map()
function to manipulate a list of strings by converting each string to uppercase.
animals = ["dog", "cat", "panda", "tiger"]
#using map() with lambda function to convert each name to uppercase
uppercase_animals = list(map(lambda x: x.upper(), animals))
print("Original names:", animals)
print("Uppercase animal names:", uppercase_animals)
#output: Original names: ['dog', 'cat', 'panda', 'tiger']
# Uppercase animal names: ['DOG', 'CAT', 'PANDA', 'TIGER']
We use the
map()
function with a lambda functionlambda x: x.upper()
to convert each animal name to uppercase.The lambda function takes one argument
x
(each animal name in the list) and returns its uppercase version using theupper()
method.The
map()
function applies this lambda function to each element of the list and returns an iterator of the results.
Lambda functions combined with higher-order functions like map()
provide a powerful way to perform operations on iterable objects in Python while keeping the code concise and readable.
PermalinkFilter Function
The filter()
function in Python is used to filter elements from an iterable based on a specified condition. It takes two arguments: a function that defines the condition, and an iterable to be filtered.
filter(function, iterable)
Suppose you want to remove empty values (" ") from the list using the filter() function with a lambda function. Here's how it will happen:
animals = ["panda", " ", "tiger", "wolf", " "]
#removinf empty strings using filter() and lambda function
filtered_list = list(filter(lambda x: x != " ", animals))
print(filtered_list) #outpu: ['panda', 'tiger', 'wolf']
We use the filter() function to remove the empty strings from the list. The filter() function takes two arguments: a function (or lambda function) that defines the condition, and the iterable.
Within the filter() function, we specify a lambda function lambda x: x != " ". This lambda function takes a single argument x (each element in the list) and returns True if the element is not an empty string (" "), and False otherwise. This lambda function acts as the filtering condition.
The filter() function iterates over each element of the list and applies the lambda function to each element. It retains elements for which the lambda function returns True (i.e., elements that are not empty strings) and discards elements for which the lambda function returns False.
PermalinkReduce Function
The reduce()
function in Python is a part of the functools
module. It applies a specified function to the elements of an iterable cumulatively to reduce it to a single value. The reduce()
function continuously applies the specified function to pairs of elements from the iterable until it is reduced to a single value.
from functools import reduce
output = reduce(function, iterable, initial)
using the reduce()
function to find the maximum element in a list:
from functools import reduce
num = [10, 30, 5, 40, 20]
#using reduce() to find the maximum element
max_num = reduce(lambda x, y: x if x > y else y, num)
print("Maximum number:", max_num) #output: Maximum number: 40
The lambda function
lambda x, y: x if x > y else y
takes two argumentsx
andy
(two consecutive elements of the list) and returns the greater of the two.The
reduce()
function applies this lambda function cumulatively to the elements of the list until it is reduced to a single value, which is the maximum element.The final maximum number is stored in the variable
max_num
and printed as output.
Subscribe to our newsletter
Read articles from directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Article Series
Python
Learning Topics
In this series, we're diving deep into Python, covering everything from the fundamental basics to ad…
Day 1 in Python
Learning Python Basics and Data Types Embarking on my first day of learning Python was an exciting j…
DAY 3 Control Flow (if, elseif, else)
Welcome back to our Python programming journey! Today, we're embarking on an exciting exploration of…
Day 4: Loops (for and while loops)
Welcome back to our Python learning journey! Today, we're going to dive into loops. Loops are a fund…
Day 5: Functions in Python
Welcome back to Day 5 of our Python blog series! Today, we are learning the concept of functions in …
Day 6: Input () Function in Python
Welcome to Day 6 of our Python blog series! Today, we're going to learn Input () function in Python …
Day 7: Working with List and Tuples in Python
Welcome to Day 7 of our Python blog series! Today, we'll explore two fundamental data structures in …
Day 8 Working with Strings in Python
Welcome to Day 8 of our Python blog series! Today, we'll dive into the world of strings in Python. S…
Day 9: List Comprehension in Python
Welcome to Day 9 of our Python blog series! Today, we'll learn a powerful and concise feature of Pyt…
Day 10: Working with Dictionaries in Python
In Python, a dictionary is a mutable, unordered collection of key-value pairs. Dictionaries are high…
Day 11: File Handling (Reading and Writing Files)
Welcome to Day 11 of our Python blog series! Today, we'll be learning file handling in Python, speci…
Day 12: Error Handling (try, except blocks)
Welcome back to our Python learning journey! Today, we're going to dive into errors. Errors in Pytho…
Day 13: Modules and Packages in Python
Welcome to Day 13 of our Python blog series! Today, we'll explore modules and packages in Python. Mo…
Day 14: Virtual Environments and Dependency Management
Welcome to Day 14 of our Python blog series! Today, we'll explore virtual environments and dependenc…
Day 15: Regular Expressions (Regex) in Python
On Day 16 of our Python blog series we'll learn Regular Expressions, commonly known as regex, in Pyt…
Day 16: Handling Dates and Times in Python
Welcome to Day 17 of our Python blog series! Today, we'll explore how to work with dates and times i…
Day 17: Debugging Techniques in Python
Welcome to Day 17 of our Python blog series! Debugging is an essential skill for every programmer. I…
Day 18: Object-Oriented Programming (OOP) in Python
Welcome to Day 18 of our Python blog series! Today, we'll explore Object-Oriented Programming (OOP) …
Day 19 : Working with CSV and JSON files in Python
Welcome to Day 19 of our Python journey! Today, we're exploring the world of data manipulation as we…
Day 21: Map() , Filter() , Reduce() and Lambda Function in Python
Functional programming is a programming prototype that emphasizes the use of functions that take inp…
Day 22: Generators and Iterators in Python
Introduction Welcome back to our Python journey! Today, we're learning iterators and generators. In …
Day 23: Decorators in Python
Welcome to Day 23 of our Python journey! Today, we're learning a powerful feature of Python: decorat…
Day 24: Threading and Multiprocessing
Introduction In the realm of software development, concurrent execution refers to the ability of a p…
Day 25: Understanding Context Managers in Python
Welcome back!!! Today's topic is Context Manager. Context managers are used to properly manage resou…
Day 25: Exploring Python Closures
Welcome back !!! Today, we'll be learning an important concept in Python programming: closures. What…
Socket in Python
Sockets in Python allows different programs on a computer or across the internet to talk to each oth…
Asynchronous Programming in Python
Imagine an ecosystem filled with animals of all shapes and sizes, each going about their tasks indep…
Python Functool
The Python programming language is known for its flexibility and powerful standard library. One modu…
Serialization & Deserialization in Python
Serialization and deserialization are the processes for transferring data between different systems …
Intro to Database
In today's world, handling lots of information is super important, and that's where databases come i…
Python SQLite
In the world of database management systems (DBMS), SQLite stands out as a lightweight yet powerful …
Data Visualization with Seaborn
Data visualization plays a crucial role in data analysis, enabling to understand trends, patterns, a…