How to Use map Function in PythonPython Basics


The map() function executes the given function for each item in an iterable.

Example

#!/usr/bin/python3
# -*- coding: UTF-8 -*-

# Calculate squares
def get_square(x):
    return x ** 2

list1=list(map(get_square, [0,1,3,4,2]))  #Convert to a list for output.
print(list1)

Output:

[0, 1, 9, 16, 4]

Syntax

map(function, iterables)

Parameters

Name Description
function The function to execute for each item.
iterables A sequence, collection, or an iterator object.

Return Value

It returns an iterator.


In this example we will show how to use the map function in Python.

Source Code

For list [1, 2, 3, 4, 5, 6, 7, 8, 9], if you want to square every element of the list, you can use the map() function:

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

def f1(x):
    return x*x

print(list(map(f1, [1, 2, 3, 4, 5, 6, 7, 8, 9])))

Output:

[1, 4, 9, 16, 25, 36, 49, 64, 81]

© 2024 Cheerlearn.com, all rights reserved. Privacy Policy | Contact Us