3

Python map() function – Tutorial

 1 year ago
source link: https://thispointer.com/python-map-function-explained-with-examples/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

In this article, we will discuss how to transform the contents of an iterable sequence using map() function. Also, we will discuss how to use the map() function with lambda functions and how to transform a dictionary using map() too.

Table Of Contents

Introduction to map() function in Python

Python provides a function map() to transform the contents of given iterable sequence based on logic provided by us i.e.

map(sequence, callback)
map(sequence, callback)

It accepts following arguments:

  • sequence : An iterable sequence
  • callback : A function that accepts an element as an argument and returns a new element based on the argument.

Returns :

  • Returns a new sequence whose size is equal to passed sequence.

How does map() function works ?

It iterates over all the elements in given sequence. While iterating the sequence it calls the given callback() function on each element and then stores the returned value in a new sequence. In the end, it returns this new sequence of transformed elements.

Now let’s see some examples of map() function,

Use map() function with list of strings and a global function

Example 1

Suppose we have a list of strings i.e.

# list of string
listOfStr = ['hi', 'this' , 'is', 'a', 'very', 'simple', 'string' , 'for', 'us']
# list of string
listOfStr = ['hi', 'this' , 'is', 'a', 'very', 'simple', 'string' , 'for', 'us']

Now let’s convert each string element in the list using map() function i.e.

def reverseStr(str):
'''Reverse a string'''
str = str[::-1]
return str
# list of string
listOfStr = ['hi', 'this' , 'is', 'a', 'very', 'simple', 'string' , 'for', 'us']
# Reverse each string in the list
modifiedList = list(map(reverseStr, listOfStr))
print('Modified List : ', modifiedList)
def reverseStr(str):
    '''Reverse a string'''
    str = str[::-1]
    return str

# list of string
listOfStr = ['hi', 'this' , 'is', 'a', 'very', 'simple', 'string' , 'for', 'us']

# Reverse each string in the list
modifiedList = list(map(reverseStr, listOfStr))

print('Modified List : ', modifiedList)

Output:

Modified List : ['ih', 'siht', 'si', 'a', 'yrev', 'elpmis', 'gnirts', 'rof', 'su']
Modified List :  ['ih', 'siht', 'si', 'a', 'yrev', 'elpmis', 'gnirts', 'rof', 'su']

As arguments, map() functions accepts our original list of string and a function reverseStr(). It iterates over all the string elements in the given list and calls the reverseStr() for each string element. Also stores the value returned by reverseStr() in a sequence. In the end, it returns the new  sequence with reversed strings.

Example 2:

We can also use the map() function to convert a list of strings to a list of numbers representing the length of each string element i.e.

listOfStr = ['hi', 'this' , 'is', 'a', 'very', 'simple', 'string' , 'for', 'us']
# Get a list of int from a list of string
modifiedList = list(map(len, listOfStr))
print('Modified List : ', modifiedList)
listOfStr = ['hi', 'this' , 'is', 'a', 'very', 'simple', 'string' , 'for', 'us']

# Get a list of int from a list of string
modifiedList = list(map(len, listOfStr))

print('Modified List : ', modifiedList)

Output:

Modified List : [2, 4, 2, 1, 4, 6, 6, 3, 2]
Modified List :  [2, 4, 2, 1, 4, 6, 6, 3, 2]

It iterates over the list of string and applies the len() function on each string element. Then stores the length returned by len() in a new sequence for every element. Then in last returns the new sequence of int i.e length of each string element.

Use map() function with lambda function

In the map() function along with iterable sequence we can also the lambda function. Let’s use lambda function to reverse each string in the list like we did above using global function,

listOfStr = ['hi', 'this' , 'is', 'a', 'very', 'simple', 'string' , 'for', 'us']
# Reverse each string in the list using lambda function & map()
modifiedList = list(map(lambda x : x[::-1], listOfStr))
print('Modified List : ', modifiedList)
listOfStr = ['hi', 'this' , 'is', 'a', 'very', 'simple', 'string' , 'for', 'us']

# Reverse each string in the list using lambda function & map()
modifiedList = list(map(lambda x : x[::-1], listOfStr))

print('Modified List : ', modifiedList)

Output:

Modified List : ['ih', 'siht', 'si', 'a', 'yrev', 'elpmis', 'gnirts', 'rof', 'su']
Modified List :  ['ih', 'siht', 'si', 'a', 'yrev', 'elpmis', 'gnirts', 'rof', 'su']

It iterates over the list of string and applies the lambda function on each string element. Then stores the value returned by lambda function to a new sequence, for each element. Then in last, returns the new sequence of reversed string elements.

Convert a string to other format using map() function in Python

We can also convert a string to another format using map() function because string is also an iterable sequence of characters. Let’s see how to transform strings using map(),

Suppose we have String i.e.

sampleStr = 'this is a secret text'
sampleStr = 'this is a secret text'

Now let’s transform this string by increment each character by 1 in it’s ascii value i.e. convert ‘a’ to ‘b’ and ‘e’ to ‘f’ etc,

# increment ascii value of each character by 1 in the string
encryptedText = ''.join(map(lambda x: chr(ord(x) + 1), sampleStr))
print('Modified Text : ', encryptedText)
# increment ascii value of each character by 1 in the string
encryptedText = ''.join(map(lambda x: chr(ord(x) + 1), sampleStr))

print('Modified Text : ', encryptedText)

Output:

Modified Text : uijt!jt!b!tfdsfu!ufyu
Modified Text :  uijt!jt!b!tfdsfu!ufyu

map() function iterated over each character in the given string and applied the given lambda function on each character to increment it’s ASCII value by 1. In the end, it returned a new string with modified content.

Passing multiple arguments to map() function in Python

In the map() function, along with a function as argument, we can also pass multiple sequence like lists as arguments. Let’s see how to pass 2 lists in the map() function and get a joined list based on them.

Suppose we have two lists i.e.

list1 = ['hi', 'this', 'is', 'a', 'very', 'simple', 'string', 'for', 'us']
list2 = [11,22,33,44,55,66,77,88,99]
list1 = ['hi', 'this', 'is', 'a', 'very', 'simple', 'string', 'for', 'us']
list2 = [11,22,33,44,55,66,77,88,99]

Now we want to join elements from list1 to list2 and create a new list of same size from these joined lists i.e. new lists should be like this,

['hi_11', 'this_22', 'is_33', 'a_44', 'very_55', 'simple_66', 'string_77', 'for_88', 'us_99']
['hi_11', 'this_22', 'is_33', 'a_44', 'very_55', 'simple_66', 'string_77', 'for_88', 'us_99']

To do that we can pass both the lists and a lambda function in map() i.e.

# Join contents of two lists using map()
modifiedList = list(map(lambda x, y: x + '_' + str(y), list1, list2))
print('Modified List : ', modifiedList)
# Join contents of two lists using map()
modifiedList = list(map(lambda x, y: x + '_' +  str(y), list1, list2))

print('Modified List : ', modifiedList)

Output:

Modified List : ['hi_11', 'this_22', 'is_33', 'a_44', 'very_55', 'simple_66', 'string_77', 'for_88', 'us_99']
Modified List :  ['hi_11', 'this_22', 'is_33', 'a_44', 'very_55', 'simple_66', 'string_77', 'for_88', 'us_99']

Here we passed a lambda function as argument. It accepts two arguments and returns a new string by join the passed arguments. Also, we passed two lists as argument to the map() function. The map() function iterates over both the lists simultaneously and pass their each element to lambda function. Then Values returned by lambda function are stored in a new list and returned in the end.

Both the lists passed to map() function should be of same size, otherwise it will through error.

Another example,

Suppose we have a lists of numbers i.e.

listOfNum = [11, 22, 33, 44, 55, 66, 77, 88, 99]
listOfNum = [11, 22, 33, 44, 55, 66, 77, 88, 99]

Now let’s multiply each element in lists by 2 and get a new lists of updated values using map() i.e.

# Multiply each element in list by 2.
modifiedList = list(map(lambda x, y: x * y, listOfNum, [2]*len(listOfNum) ))
print('Modified List : ', modifiedList)
# Multiply each element in list by 2.
modifiedList = list(map(lambda x, y: x * y, listOfNum, [2]*len(listOfNum) ))

print('Modified List : ', modifiedList)

Output:

Modified List : [22, 44, 66, 88, 110, 132, 154, 176, 198]
Modified List :  [22, 44, 66, 88, 110, 132, 154, 176, 198]

Using map() function to transform Dictionaries in Python

Suppose we have a dictionary i.e.

dictOfNames = {
7 : 'sam',
8: 'john',
9: 'mathew',
10: 'riti',
11 : 'aadi',
12 : 'sachin'
dictOfNames = {
    7 : 'sam',
    8: 'john',
    9: 'mathew',
    10: 'riti',
    11 : 'aadi',
    12 : 'sachin'
}

Now we want to transform the values in dictionary by appending ‘_’ at the end of each value i.e.

# add an '_' to the value field in each key value pair of dictionary
dictOfNames = dict(map(lambda x: (x[0], x[1] + '_'), dictOfNames.items() ))
print('Modified Dictionary : ')
print(dictOfNames)
# add an '_' to the value field in each key value pair of dictionary
dictOfNames = dict(map(lambda x: (x[0], x[1] + '_'), dictOfNames.items() ))

print('Modified Dictionary : ')
print(dictOfNames)

Output:

Modified Dictionary :
{7: 'sam_', 8: 'john_', 9: 'mathew_', 10: 'riti_', 11: 'aadi_', 12: 'sachin_'}
Modified Dictionary : 
{7: 'sam_', 8: 'john_', 9: 'mathew_', 10: 'riti_', 11: 'aadi_', 12: 'sachin_'}

the map() function iterated over all the items in dictionary and then applied passed lambda function on each item. Which in turn updated the value of each item and returns a copy of original dictionary with updated contents.

The Complete example is as follows:

def reverseStr(str):
'Reverse a string'
str = str[::-1]
return str
print('*** Use map() function with list of strings and global functions ***')
# list of string
listOfStr = ['hi', 'this' , 'is', 'a', 'very', 'simple', 'string' , 'for', 'us']
# Reverse each string in the list
modifiedList = list(map(reverseStr, listOfStr))
print('Modified List : ', modifiedList)
# Get a list of int from a list of string
modifiedList = list(map(len, listOfStr))
print('Modified List : ', modifiedList)
print('*** Using map() function with lambda function ***')
# Reverse each string in the list using lambda function & map()
modifiedList = list(map(lambda x : x[::-1], listOfStr))
print('Modified List : ', modifiedList)
print('**** Convert a string to other format using map() ****')
sampleStr = 'this is a secret text'
print('Original Text : ', sampleStr)
# increment ascii value of each character by 1 in the string
encryptedText = ''.join(map(lambda x: chr(ord(x) + 1), sampleStr))
print('Modified Text : ', encryptedText)
print('*** Passing multiple arguments to map() function ***')
list1 = ['hi', 'this', 'is', 'a', 'very', 'simple', 'string', 'for', 'us']
list2 = [11,22,33,44,55,66,77,88,99]
# Join contents of two lists using map()
modifiedList = list(map(lambda x, y: x + '_' + str(y), list1, list2))
print('Modified List : ', modifiedList)
print('*** Multiply each element in lists by a number ***')
listOfNum = [11, 22, 33, 44, 55, 66, 77, 88, 99]
# Multiply each element in list by 2.
modifiedList = list(map(lambda x, y: x * y, listOfNum, [2]*len(listOfNum) ))
print('Modified List : ', modifiedList)
print('*** Using map() with dictionaries ****')
# Transform all the values of a dictionary using map()
dictOfNames = {
7 : 'sam',
8: 'john',
9: 'mathew',
10: 'riti',
11 : 'aadi',
12 : 'sachin'
print('Original Dictionary : ')
print(dictOfNames)
# add an '_' to the value field in each key value pair of dictionary
dictOfNames = dict(map(lambda x: (x[0], x[1] + '_'), dictOfNames.items() ))
print('Modified Dictionary : ')
print(dictOfNames)
def reverseStr(str):
    'Reverse a string'
    str = str[::-1]
    return str

print('*** Use map() function with list of strings and global functions ***')
# list of string
listOfStr = ['hi', 'this' , 'is', 'a', 'very', 'simple', 'string' , 'for', 'us']

# Reverse each string in the list
modifiedList = list(map(reverseStr, listOfStr))

print('Modified List : ', modifiedList)

# Get a list of int from a list of string
modifiedList = list(map(len, listOfStr))

print('Modified List : ', modifiedList)

print('*** Using map() function with lambda function ***')

# Reverse each string in the list using lambda function & map()
modifiedList = list(map(lambda x : x[::-1], listOfStr))

print('Modified List : ', modifiedList)

print('**** Convert a string to other format using map() ****')

sampleStr = 'this is a secret text'

print('Original Text : ', sampleStr)

# increment ascii value of each character by 1 in the string
encryptedText = ''.join(map(lambda x: chr(ord(x) + 1), sampleStr))

print('Modified Text : ', encryptedText)

print('*** Passing multiple arguments to map() function ***')

list1 = ['hi', 'this', 'is', 'a', 'very', 'simple', 'string', 'for', 'us']
list2 = [11,22,33,44,55,66,77,88,99]

# Join contents of two lists using map()
modifiedList = list(map(lambda x, y: x + '_' +  str(y), list1, list2))

print('Modified List : ', modifiedList)

print('*** Multiply each element in lists by a number ***')

listOfNum = [11, 22, 33, 44, 55, 66, 77, 88, 99]

# Multiply each element in list by 2.
modifiedList = list(map(lambda x, y: x * y, listOfNum, [2]*len(listOfNum) ))

print('Modified List : ', modifiedList)

print('*** Using map() with dictionaries ****')

# Transform all the values of a dictionary using map()

dictOfNames = {
    7 : 'sam',
    8: 'john',
    9: 'mathew',
    10: 'riti',
    11 : 'aadi',
    12 : 'sachin'
}

print('Original Dictionary : ')
print(dictOfNames)

# add an '_' to the value field in each key value pair of dictionary
dictOfNames = dict(map(lambda x: (x[0], x[1] + '_'), dictOfNames.items() ))

print('Modified Dictionary : ')
print(dictOfNames)

Output:

*** Use map() function with list of strings and global functions ***
Modified List : ['ih', 'siht', 'si', 'a', 'yrev', 'elpmis', 'gnirts', 'rof', 'su']
Modified List : [2, 4, 2, 1, 4, 6, 6, 3, 2]
*** Using map() function with lambda function ***
Modified List : ['ih', 'siht', 'si', 'a', 'yrev', 'elpmis', 'gnirts', 'rof', 'su']
**** Convert a string to other format using map() ****
Original Text : this is a secret text
Modified Text : uijt!jt!b!tfdsfu!ufyu
*** Passing multiple arguments to map() function ***
Modified List : ['hi_11', 'this_22', 'is_33', 'a_44', 'very_55', 'simple_66', 'string_77', 'for_88', 'us_99']
*** Multiply each element in lists by a number ***
Modified List : [22, 44, 66, 88, 110, 132, 154, 176, 198]
*** Using map() with dictionaries ****
Original Dictionary :
{7: 'sam', 8: 'john', 9: 'mathew', 10: 'riti', 11: 'aadi', 12: 'sachin'}
Modified Dictionary :
{7: 'sam_', 8: 'john_', 9: 'mathew_', 10: 'riti_', 11: 'aadi_', 12: 'sachin_'}
*** Use map() function with list of strings and global functions ***
Modified List :  ['ih', 'siht', 'si', 'a', 'yrev', 'elpmis', 'gnirts', 'rof', 'su']
Modified List :  [2, 4, 2, 1, 4, 6, 6, 3, 2]
*** Using map() function with lambda function ***
Modified List :  ['ih', 'siht', 'si', 'a', 'yrev', 'elpmis', 'gnirts', 'rof', 'su']
**** Convert a string to other format using map() ****
Original Text :  this is a secret text
Modified Text :  uijt!jt!b!tfdsfu!ufyu
*** Passing multiple arguments to map() function ***
Modified List :  ['hi_11', 'this_22', 'is_33', 'a_44', 'very_55', 'simple_66', 'string_77', 'for_88', 'us_99']
*** Multiply each element in lists by a number ***
Modified List :  [22, 44, 66, 88, 110, 132, 154, 176, 198]
*** Using map() with dictionaries ****
Original Dictionary : 
{7: 'sam', 8: 'john', 9: 'mathew', 10: 'riti', 11: 'aadi', 12: 'sachin'}
Modified Dictionary : 
{7: 'sam_', 8: 'john_', 9: 'mathew_', 10: 'riti_', 11: 'aadi_', 12: 'sachin_'}

Pandas Tutorials -Learn Data Analysis with Python

 

 

Are you looking to make a career in Data Science with Python?

Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.

Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.

Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.

Join a LinkedIn Community of Python Developers

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK