Python Built-in functions lambda, map, filter, reduce.

Author: neptune | 15th-Jun-2023
#Python

1. Lambda

Lambda function is used to create a small anonymous function. Lambda is a powerful python function with some limited capabilities. Lambda function can accept any number of elements as input but only one expression is evaluated and returned.


Why Use Lambda Function?

Lambda function is preffered for writing single line function instead of using normal functions. For writing a normal function we need to use def keyword to define a function and return keyword is used to return value from function.

Lambda function requires a lambda keyword to define a lambda function and don’t need any keyword for return values from lambda functions.


Syntax

For single Input

lambda <argument>: <Calculation or Evaluation>

For Multiple Input

lambda <argument1,argument2,argument3..>: <Calculation or Evaluation>



Examples

Addition of one Variable

lambda a : a+10

Above function accepts onr variable "a" and returns it after adding 10 into it.


Addition of Two Variables

lambda a,b : a+b

Above function accepts two variables "a" and "b" and return addition of a and b.

1. Addition of one Variable

Using Normal Function

# Create a Function To Add 10 To Input Number
def Add(a):
return a+10

result = Add(5)
print(result)

output:
15

Using Lambda Function

# Create a Lambda Function
Add = lambda a : a+10
result = Add(5)
print(result)

Output:
15





2. Addition of Two Variables

Using Normal Function

# Create a Function to accept two number and returns addition
def Add(a,b):
return a+b

result = Add(5,6)
print(result)

output:
11

Using Lambda Function

Add = lambda a,b : a+b
result = Add(5,6)
print(result)

Output:
11


3. Addition of Two numbers List

# Define Two Lists
lst1 = [1,2,3,4]
lst2 = [5,6,7,8]

# Use of Multiple Parameter as input
Addition = map(lambda a,b:a+b,lst1,lst2)

print(f" List 1 : {lst1} \n List 2 : {lst2}")

# Convert mapped object to list
final_result = list(Addition)
print(f" Addition of List1 and List2 : {final_result}")

Output:
List 1 : [1, 2, 3, 4]
List 2 : [5, 6, 7, 8]
Addition of List1 and List2 : [6, 8, 10, 12]

Lambda Function can be used with map, filter, reduce python built-in functions

  • map
  • filter
  • reduce

Note: Lambda Function has some limited capabilities such as only one expression can be evaluated.





2. map

map is used to apply a specific function on every element of an iterable object such as list, tuple, strings etc.

Map returns a mapped object after applying function to every element from iterable object. Map can be used with both normal functions or lambda function.

Syntax

map(func, *iterables)

Where
func : Normal function or a Lambda function.
iterbales: Any iterable Object such as list, string, tuple etc.


Examples

We are going to apply map() on multiple examples. And compare examples with both user defined function and a lambda function.

1. Add 5 to every element of list using (user defined function)

# add 5 to given input elements
def Add(a):
return a+5

# A Sample list
lst = [1,2,3,4]

# Apply Add Function to lst with map()
result = list(map(Add,lst))
print(f" Result: {result}")

Result: [5,7,8,9]

Add 5 to every list elements using lambda function.

# A Sample list
lst = [1,2,3,4]

# Apply Add Function to lst with map()
result = map(lambda a : a+5,lst)
final_result = list(result)
print(f"Result: {result}")

output:
Result: [6,7,8,9]


2. Convert a string numbers into int numbers in lst.

# A Sample strings numbers list
lst = ['1','2','3','4']

# Conversion into int
result = map(int,lst)

# Type cast map object to list
final_result = list(result)

print(f"Int List(After Conversion): {final_result}")

Output:
Int List(After Conversion) : [1, 2, 3, 4]

If we check the datatype of list elements before then after then we get following result.

# Original List (Datatype)
type(lst[0])
<class 'str'>

# Converted List (Datatype)
type(final_result[0])
<class 'int'>


3. Filter

Filter is used to filter out records from an iterable object based on condition evaluated from a function. It function is applicable to every element of an iterable object.

Filter added the element to the final list only if applied function returns True Otherwise that element is excluded.

Syntax

filter(function or None, iterable)

Where
function : any user defined normal function or lambda function. iterable : any iterable Object such as list, tuple, strings etc.


Example: 1

Filter Even numbers from given input list using filter.

# Define a  List
lst = [1,2,3,4,5,6,7,8]

# Filter out odd Numbers
odd_numbers = filter(lambda a:a%2!=0,lst)

# Filter out Even Numbers
even_numbers = filter(lambda a:a%2==0,lst)

print(f" List : {lst}")

# Convert mapped object to list
odd_result = list(odd_numbers)
even_result = list(even_numbers)

print(f"Filtered List(Odd) : {odd_result}")
print(f"Filtered List(Even) : {even_result}")

Output:
List : [1, 2, 3, 4, 5, 6, 7, 8]
Filtered List(Odd) : [1, 3, 5, 7]
Filtered List(even) : [2, 4, 6, 8]

Example: 2

Filter Uppercase letters using filter.

# Define a  string
text = "PyThOn"

# Filter out Capital Letters
uppercase_alpha = filter(lambda a:a.isupper(),text)

# Convert mapped object to list
final_result = list(uppercase_alpha)

print(f"text : {text}")
print(f"Uppercase Letters : {final_result}")

Output:
text : PyThOn
Uppercase Letters : ['P', 'T', 'O']


4. Reduce

Reduce function is not a part of python built-in function you need to import it from functools.It is used to reduce an iterable object to a single value by combining elements via a applied function.

Syntax

from functools import reduce
result = reduce(function, iterable)

Where
function : Any lambda or normal user defined function.
sequence : any sequence iterable list

Example

# Define a list
lst = [1,2,3,4,5]

# Import reduce from functools
from functools import reduce
result = reduce(lambda a,b :a+b,lst)
print(f"Addition of All Elements in List is : {result}")

Output:
Addition of All Elements in Lst1 is : 15

# without reduce
val = ((((1+2)+3)+4)+5)
print(val)
15

Self Practice exercise

1. Write a Program using lambda to calculate square of given user input radius.
2. Write a Program using lambda to multiply three elements.
3. Write a Program For Addition of Following Lists.
Lst1 = [0,1,2]
Lst2 = ["3","4","5"]
4. Write a Program to find out numbers from range(1,121) divisible by 3,
5. Write a Program to calculate sum of odd numbers (1,100)
6. Write a program to convert List element to int
Lst = ["3","4","5"]

If you have any questions or suggestions in the comments section below, follow us on social media for more such articles.

Thanks for reading!



Related Blogs
How to extract Speech from Video using Python?
Author: neptune | 16th-Jun-2023
#Python #Projects
Simple and easy way to convert video into audio then text using Google Speech Recognition API...

How to download video from youtube using python module ?
Author: neptune | 15th-Jun-2023
#Python
We will let you know how you can easily download the Youtube high quality videos along with subtitle, thumbnail, description using python package..

Best Python package manager and package for virtual environment ?
Author: neptune | 18th-Jun-2023
#Python #Pip
We will explore the options of Pip, Virtualenv, Anaconda, and also introduce Pyenv as a helpful tool...

Deploy Django project on AWS with Apache2 and mod_wsgi module.
Author: neptune | 18th-May-2024
#Python #Django
In this blog I use the AWS Ubuntu 18.22 instance as Hosting platform and used Apache2 server with mod_wsgi for configurations. We create a django sample project then configure server...

Mostly asked Python Interview Questions - 2023.
Author: neptune | 30th-May-2023
#Python #Interview
Python interview questions for freshers. These questions asked in 2022 Python interviews...

Core Python Syllabus for Interviews
Author: neptune | 26th-Jul-2023
#Python #Interview
STRING MANIPULATION : Introduction to Python String, Accessing Individual Elements, String Operators, String Slices, String Functions and Methods...

How to reverse string in Python ?
Author: neptune | 16th-May-2022
#Python
We are going to explore different ways to reverse string in Python...

Python 3.9 new amazing features ?
Author: neptune | 26th-Jul-2023
#Python
Python 3.9 introduces new features such as dictionary union, string methods to remove prefixes and suffixes, type hinting, and speed improvements for built-in functions...

5 Languages that Replace Python with Proof
Author: neptune | 13th-Apr-2023
#Python
Julia, Rust, Go, Kotlin, and TypeScript are modern languages that could replace Python for specific use cases...

10 Proven Ways to Earn Money Through Python
Author: neptune | 11th-Apr-2023
#Python
Python offers numerous earning opportunities from web development to teaching, data analysis, machine learning, automation, web scraping, and more...

Monkey Patching in Python: A Powerful Yet Controversial Technique
Author: neptune | 01st-Aug-2023
#Python
Monkey patching in Python is a dynamic technique to modify code at runtime. It can add/alter behavior, but use it judiciously to avoid maintainability issues...

Building a Simple Chatbot with Python and openpyxl
Author: neptune | 25th-Jun-2024
#Python #Projects
This chatbot reads questions and answers from an Excel file and provides responses based on user input...

Best Practices for Managing Requests Library Sessions When Interacting with Multiple APIs ?
Author: neptune | 22nd-Aug-2024
#Python
When working with Python's `requests` library, managing sessions is crucial, especially when your application interacts with multiple APIs...

How to Update XML Files in Python?
Author: neptune | 01st-Jul-2024
#Python
Handling XML files in Python is straightforward with the `xml.etree.ElementTree` module...

How to Ensure Proper Namespace Handling in XML with Python's lxml Library
Author: neptune | 01st-Jul-2024
#Python
By using `lxml`, you can effectively manage XML namespaces and ensure that your XML structure remains intact during updates...

View More