"map" in python

Home Forums Python Programming "map" in python

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #1958 Reply
    Humble
    Keymaster

    map accepts 2 arguments .. first arg is the function and second arg is the sequence .. so it got below form:

    map(func, seq)

    Now the sequence is not restricted to “1”, it can have more than 1 sequence.. how-ever those have to be of the same length..

    In that case, the function will be applied to each index in all the sequences..

    for ex:

    >>>> l = [1,10,100]
    >>> m = [2,20,200]
    >>> map(lambda x,y: x/y, l,m)
    [0, 0, 0]
    >>> map(lambda x,y: x%y, l,m)
    [1, 10, 100]
    >>> map(lambda x,y: x*y, l,m)
    [2, 200, 20000]
    >>>
    
    
    
    map() is well used with the combination of lambda functions as you can see in the above example.
    
    In short , To apply an operation to each item in a sequence/list and to collect the result, the map() will be really useful..
    
    map call is similar to list comprehension..
    #1968 Reply
    Humble
    Keymaster

    In python3 or above, the “return” of map() will be shown as an object: You need to input that to list to see the desired result..

    Code:
    >>> l = [1,10,100]
    >>> m = [2,20,200]
    >>> map(lambda x,y: x*y, l,m)
    <map object at 0x7f7753fcb790>
    >>> list(map(lambda x,y: x*y, l,m))
    [2, 200, 20000]
    >>>

    #1969 Reply
    Humble
    Keymaster

    Also, if first arg (ie: func ) is “none”, the map() returns the elements of iteratable object as a tuple…

Viewing 3 posts - 1 through 3 (of 3 total)
Reply To: "map" in python
Your information: