Python : map() Function with Examples

In this article, we will look at how to use map to transform the contents of an iterable sequence (). We’ll also go over how to use the map() function with lambda functions and how to use map() to transform a dictionary.

Map() function in Python

1)map() function details

Syntax:

map(function, iterable)

Parameters:

function :   It is a function to which each element of a given iterable is passed.
Iterable  :   It is an iterable that is to be mapped.

Return :

The map() feature applies to each item of an iterable function and returns the results list.

You can then pass the return value from map() (map object) to functions like list() (to create a list), set() (to create a set), etc.

2)Working of map function

In the given sequence, it iterates across all elements. It calls the given callback() function on every item and then stores the returned value in a new sequence during iteration of the sequence. Ultimately this new transformed element sequence will return.

Examples:

3)Squaring each list element using map

By writing a function that squares the number, we can square each list element.

Below is the implementation:

# function which squares the number
def squareNumber(number):
# square the number
return number*number

# given list
givenlist = [5, 2, 6, 9]
# using map function to square each list element
squarelist = list(map(squareNumber, givenlist))
# print squarelist
print(squarelist)


Output:

[25, 4, 36, 81]

4)Reverse each string in list

By writing a function which reverses the string, we can reverse each list element.

Below is the implementation:

# function which reverses the string
def revString(string):
# reverse the string
return string[::-1]

# given list
givenlist = ['hello', 'this', 'is', 'BTechGeeks']
# using map function to reverse each string in list
reverselist = list(map(revString, givenlist))
# print squarelist
print(reverselist)


Output:

['olleh', 'siht', 'si', 'skeeGhceTB']

We can add two lists by using lambda function

Below is the implementation:

# given lists
list1 = [9, 3, 4]
list2 = [4, 8, 6]
# using map function to sum the two lists
sumlist = list(map(lambda a, b: a + b, list1, list2))
# print sumlist
print(sumlist)


Output:

[13, 11, 10]

Related Programs: