In this article we will discuss how to transform the contents of a iterable sequence using map(). Also we will discuss how to use map() function with lambda functions and how to transform a dictionary using map() too.
Python’s map() Function
Python provides a function map() to transform the contents of given iterable sequence based on logic provided by us i.e.
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 return 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
Suppose we have a list of strings i.e.
# 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.
# 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']
As arguments, map() functions accepts our original list of string and a function reverseStr(). It iterates over all the string elements in our list
and calls 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.
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)
Output:
Modified List : [2, 4, 2, 1, 4, 6, 6, 3, 2]
It iterates over the list of string and apply 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)
Output:
Modified List : ['ih', 'siht', 'si', 'a', 'yrev', 'elpmis', 'gnirts', 'rof', 'su']
It iterates over the list of string and apply 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'
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)
Output:
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
The map() function, along with a function as argument can also pass multiple sequence like lists as arguments. Let’s see how to pass 2 lists in
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]
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']
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)
Output:
Modified List : ['hi_11', 'this_22', 'is_33', 'a_44', 'very_55', 'simple_66', 'string_77', 'for_88', 'us_99']
Here passed lambda function accepts two arguments and returns a new string by join the passed arguments. 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]
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)
Output:
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' }
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)
Output:
Modified Dictionary : {7: 'sam_', 8: 'john_', 9: 'mathew_', 10: 'riti_', 11: 'aadi_', 12: 'sachin_'}
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.
Complete example is as follows:
def reverseStr(str): 'Reverse a string' str = str[::-1] return str def main(): 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) if __name__ == '__main__': main()
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_'}
Pandas Tutorials -Learn Data Analysis with Python
-
Pandas Tutorial Part #1 - Introduction to Data Analysis with Python
-
Pandas Tutorial Part #2 - Basics of Pandas Series
-
Pandas Tutorial Part #3 - Get & Set Series values
-
Pandas Tutorial Part #4 - Attributes & methods of Pandas Series
-
Pandas Tutorial Part #5 - Add or Remove Pandas Series elements
-
Pandas Tutorial Part #6 - Introduction to DataFrame
-
Pandas Tutorial Part #7 - DataFrame.loc[] - Select Rows / Columns by Indexing
-
Pandas Tutorial Part #8 - DataFrame.iloc[] - Select Rows / Columns by Label Names
-
Pandas Tutorial Part #9 - Filter DataFrame Rows
-
Pandas Tutorial Part #10 - Add/Remove DataFrame Rows & Columns
-
Pandas Tutorial Part #11 - DataFrame attributes & methods
-
Pandas Tutorial Part #12 - Handling Missing Data or NaN values
-
Pandas Tutorial Part #13 - Iterate over Rows & Columns of DataFrame
-
Pandas Tutorial Part #14 - Sorting DataFrame by Rows or Columns
-
Pandas Tutorial Part #15 - Merging or Concatenating DataFrames
-
Pandas Tutorial Part #16 - DataFrame GroupBy explained with examples
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.