Python map() function with Examples

Posted in /  

Python map() function with Examples
vinaykhatri

Vinay Khatri
Last updated on December 22, 2024

    The Python map() function is a Python built-in function. The map() function can apply a specific function definition on all the items present in the given Python iterator(string, list, tuple, dictionary, etc). Here in this tutorial, we will learn How to use the Python map() function and discuss see some of its examples with various Python iterators .

    What is Python map() function?

    The Python map() function is a simple and powerful Python function or method which is generally used when we want to apply a specific function on every element of iterator object like list, dictionary, tuple, set, and string.

    Python map() function syntax

    map(function_name, iterator_object1, iterator_object2)

    The Python map() function generally accept two parameters

    • Function name represents the function that will be applied to every element or item present in the iterator. The function name could be Python user-defined function , Python inbuilt function, or Python lambda function .
    • iterator represents a Python iterator object such as list, tuple, etc on which elements the function will be applied.

    Python map() function return value

    The map() function return an iterable <map> object, and using list, tuple, or set we can convert the map object to the corresponding list, tuple or set.

    Working of Python map() function

    The map() function generally accepts two parameters, the function, and iterable object . The map() function picks every element from the iterable objects one by one and passes it to the specified function. And store the return values as a map iterable object. If the specified function needs more than one, in that case we need to specify more than one iterable object of the same shape.

    Python map() function with two parameters Example

    def multiple3(num):
        return num *3
    
    my_list = [1,2,3,4,5,6,7]
    
    map_instance = map(multiple3, my_list)
    
    print("map_instance value is:", map_instance)
    
    print("Convert map_instance to list:", list(map_instance) )

    Output

    map_instance value is: <map object at 0x03A82178>
    Convert map_instance to list: [3, 6, 9, 12, 15, 18, 21]

    As in the above example, you can see that the map() function return a <map> object  after applying the function multiple3 on every my_list element. In the above example, the multiple3(num) function only accepts single argument num that’s why we only defined a single iterable object my_list. If the specified function needs more than one parameter, there you need to define more than one iterable object.

    Python map function with more than 2 parameters Example

    def multiply(num1, num2):
        return num1* num2
    
    my_list1 = [1,2,3,4,5,6,7]
    
    my_list2 = [1,2,3,4,5,6,7]
    
    map_instance = map(multiply, my_list1, my_list2)
    
    #convert the map object to list
    print("The result is: ", list(map_instance) )

    Output

    The result is:  [1, 4, 9, 16, 25, 36, 49]

    Iterate over the map object

    By far, to see the result of the map() function we convert the map _ instance to the list by using the Python list() function . As the map() function returns a map iterable object and we could also use the for loop to iterate over map object and grab all values.

    Example

    def multiply(num1, num2):
        return num1* num2
    
    my_list1 = [1,2,3,4,5,6,7]
    
    my_list2 = [1,2,3,4,5,6,7]
    
    map_instance = map(multiply, my_list1, my_list2)
    
    #iterate over map object
    for value in map_instance:
        print(value)

    Output

    1
    4
    9
    16
    25
    36
    49

    How to use Python map() function with Python built-in functions/method

    The Python map() function can be used with Python's built-in functions, and as a normal function, you just need to mention the built-in function name as the first parameter of the map() function. With the help of Python map() and other built-in functions like float(), str(), math.ceil(), math.floor(), etc. we can apply all those functions to an iterable object all elements. For instance, if you have a list of floating-point numbers and you want a tuple of integer values of the same floating numbers list. So, instead of creating a for loop, traverse through list of floating numbers and convert every element using int() method, and add them to the tuple, we can simply use the Python map() function. And it will do all those things within a single line of code.

    Example

    float_list = [12.3, 23.2, 34.23, 36.56, 70.78, 79.41]
    
    int_tuple = tuple( map(int, float_list))
    
    print("The value of int_tuple is:", int_tuple)

    Output

    The value of int_tuple is: (12, 23, 34, 36, 70, 79)

    The map(int, float_list) , statement pass all float_list elements to the Python int() method and store the returned value. At last, the tuple() function convert the map object to the tuple object.

    How to use Python string iterator with Python map() function?

    The Python string is also an iterable object. And like other iterators, it can be passed as the second parameter to the map(function, string) function. The map() function applies the specified function to every character of the string.

    Example

    def vowelUpper(char):
        if char in "aeiou":
            return char.upper()
        else:
            return char
    
    string = "Welcome to Techgeekbuzz.com"
    
    map_obj = map(vowelUpper, string)
    
    #convert map() object to string
    caps_vowel =  "".join(list(map_obj))
    
    print(caps_vowel) 

    Output

    WElcOmE tO TEchgEEkbUzz.cOm

    Note: We cannot use the str() method to convert the map() object values to a string object.

    How to use Python map() function with Python tuple

    A Python tuple is an iterable object. It is an immutable data structure that store elements using rounded brackets and separate them with comma. Let’s see an example where we use a tuple iterator as a second parameter to the map() function and convert every tuple integer and floating-point number to a string.

    Example

    num_tup = (1, 1.34, 3, 4.34, 7, 8.9)
    
    map_obj = map(str, num_tup)
    
    #convert map() object to tuple
    str_tuple =  tuple(map_obj)
    
    print(str_tuple)

    Output

    ('1', '1.34', '3', '4.34', '7', '8.9')

    How to use Python map() function with Python dictionary

    The Python dictionary is a collection of key:value pairs. It is also an iterable object, and by default, the iteration only occurred in the key section of the dictionary.

    Example

    def add10(key):
        return key+10
    
    my_dict = {1:100, 2:200, 3:300, 4:400, 5:500}
    
    map_obj = map(add10, my_dict)
    
    #convert map object to list
    key_list =list(map_obj)
    
    print(key_list)

    Output

    [11, 12, 13, 14, 15]

    In the above example, you can see that the map(add10, my_dict) statement only applied the add10 function to the my_dict key’s not values. If you want to apply the function to dictionary values, you need to pass the dictionary values as an iterable object.

    Example

    def add10(value):
        return value+10
    
    my_dict = {1:100, 2:200, 3:300, 4:400, 5:500
    
    #map will pass my_dict values to add10
    map_obj = map(add10, my_dict.values())
    
    #convert map object to list
    value_list =list(map_obj)
    
    print(value_list)

    Output

    [110, 210, 310, 410, 510]

    You can also access both keys and values of a Dictionary using the dictionary items() method.

    Example

    def add10(item):
        key= item[0]
        value = item[1]
        return key+10, value+10
    
    my_dict = {1:100, 2:200, 3:300, 4:400, 5:500}
    
    map_obj = map(add10, my_dict.items())
    
    #convert map object to dict
    new_dict =dict(map_obj)
    
    print(new_dict)

    Output

    {11: 110, 12: 210, 13: 310, 14: 410, 15: 510}

    How to use Python map() function with Python set()

    Set is a Python built-in data structure that only stores unique elements or values. It is also an iterable object and can be used as an iterator object parameter to the map() function

    Example

    def add1(value):
        return value+1
    
    my_set = {20, 40, 50, 60, 80}
    
    map_obj = map(add1, my_set)
    
    #convert map object to set
    new_set =set(map_obj)
    
    print(new_set)

    Output

    {41, 81, 51, 21, 61}

    How to use Python map() function with Python Lambda Function

    Python Lambda Functions aka Python Anonymous Functions, are often used with map() functions. Lambda function provides an alternative way to define a function without using any function name. And map() statement is the place where lambda functions excel. The lambda function can be defined as the first parameter of map() function.

    Example

    my_list = [20, 40, 50, 60, 80]
    
    my_sq_list = list(map(lambda num:num**2, my_list))
    
    print(my_sq_list)

    Output

    [400, 1600, 2500, 3600, 6400]

    Conclusion

    The map() function is an inbuilt Python function that returns an iterable <map> object. It generally accepts two parameters function (f) and iterable objects . The number of iterable objects depends on the number of parameters accepted by the function (f). You can iterate over a map object using Python for loop . And it can also be changed or converted to Python list, dictionary, tuple, and set using list(), dict(), tuple() and set() functions.

    People are also reading:

    Leave a Comment on this Post

    0 Comments