Python Language


Map Function All Versions

Python 2.x

2.0
2.1
2.2
2.3
2.4
2.5
2.6
2.7

Python 3.x

3.0
3.1
3.2
3.3
3.4
3.5
3.6

This draft deletes the entire topic.

Introduction

Introduction

expand all collapse all

Examples

  • 19

    The map function is the simplest one among Python built-ins used for functional programming. map() applies a specified function to each element in an iterable:

    names = ['Fred', 'Wilma', 'Barney']
    
    Python 3.x3.0
    map(len, names)  # map in python 3.x is a class; its instances are iterable
    # Out: <map object at 0x00000198B32E2CF8>
    
    Python 2.x2.6
    from future_builtins import map  # contains a python 3.x compatible map()
    map(len, names)                  # see below
    # Out: <itertools.imap instance at 0x3eb0a20>
    
    Python 2.x2.3
    map(len, names)   # map() returns a list
    # Out: [4, 5, 6]
    
    from itertools import imap
    imap(len, names)  # itertools.imap() returns a generator
    # Out: <itertools.imap at 0x405ea20>
    

    The result can be explicitly converted to a list to remove the differences:

    list(map(len, names))
    # Out: [4, 5, 6]
    

    map() can be replaced by an equivalent list comprehension or generator expression:

    [len(item) for item in names] # equivalent to python 2.x map()
    # Out: [4, 5, 6]
    
    (len(item) for item in names) # equivalent to python 3.x map()
    # Out: <generator object <genexpr> at 0x00000195888D5FC0>
    
  • 13

    For example, you can take the absolute value of each element:

    list(map(abs, (1, -1, 2, -2, 3, -3))) # the call to `list` is unnecessary in 2.x
    # Out: [1, 1, 2, 2, 3, 3]
    

    Anonymous function also support for mapping a list:

    map(lambda x:x*2, [1, 2, 3, 4, 5])
    # Out: [2, 4, 6, 8, 10]
    

    or converting decimal values to percentages:

    def to_percent(num):
        return num * 100
    
    list(map(to_percent, [0.95, 0.75, 1.01, 0.1]))
    # Out: [95.0, 75.0, 101.0, 10.0]
    

    or converting dollars to euros (given an exchange rate):

    from functools import partial
    from operator import mul
    
    rate = 0.9  # fictitious exchange rate, 1 dollar = 0.9 euros
    dollars = {'under_my_bed': 1000,
               'jeans': 45,
               'bank': 5000}
    
    sum(map(partial(mul, rate), dollars.values()))
    # Out: 5440.5
    

    functools.partial is a convenient way to fix parameters of functions so that they can be used with map instead of using lambda or creating customized functions.

  • 5

    For example calculating the average of each i-th element of multiple iterables:

    def average(*args):
        return float(sum(args)) / len(args)  # cast to float - only mandatory for python 2.x
    
    measurement1 = [100, 111, 99, 97]
    measurement2 = [102, 117, 91, 102]
    measurement3 = [104, 102, 95, 101]
    
    list(map(average, measurement1, measurement2, measurement3))
    # Out: [102.0, 110.0, 95.0, 100.0]
    

    There are different requirements if more than one iterable is passed to map depending on the version of python:

    • The function must take as many parameters as there are iterables:

      def median_of_three(a, b, c):
          return sorted((a, b, c))[1]
      
      list(map(median_of_three, measurement1, measurement2))
      

      TypeError: median_of_three() missing 1 required positional argument: 'c'

      list(map(median_of_three, measurement1, measurement2, measurement3, measurement3))
      

      TypeError: median_of_three() takes 3 positional arguments but 4 were given

    Python 2.x2.0.1
    • map: The mapping iterates as long as one iterable is still not fully consumed but assumes None from the fully consumed iterables:

      import operator
      
      measurement1 = [100, 111, 99, 97]
      measurement2 = [102, 117]
      
      # Calculate difference between elements
      list(map(operator.sub, measurement1, measurement2))
      

      TypeError: unsupported operand type(s) for -: 'int' and 'NoneType'

    • itertools.imap and future_builtins.map: The mapping stops as soon as one iterable stops:

      import operator
      from itertools import imap
      
      measurement1 = [100, 111, 99, 97]
      measurement2 = [102, 117]
      
      # Calculate difference between elements
      list(imap(operator.sub, measurement1, measurement2))
      # Out: [-2, -6]
      list(imap(operator.sub, measurement2, measurement1))
      # Out: [2, 6]
      
    Python 3.x3.0.0
    • The mapping stops as soon as one iterable stops:

      import operator
      
      measurement1 = [100, 111, 99, 97]
      measurement2 = [102, 117]
      
      # Calculate difference between elements
      list(map(operator.sub, measurement1, measurement2))
      # Out: [-2, -6]
      list(map(operator.sub, measurement2, measurement1))
      # Out: [2, 6]
      
Please consider making a request to improve this example.

Syntax

  • map(function, iterable[, *additional_iterables])
  • future_builtins.map(function, iterable[, *additional_iterables])
  • itertools.imap(function, iterable[, *additional_iterables])

Parameters

ParameterDetails
functionfunction for mapping (must take as many parameters as there are iterables) (positional-only)
iterablethe function is applied to each element of the iterable (positional-only)
*additional_iterablessee iterable, but as many as you like (optional, positional-only)

Remarks

Everything that can be done with map can also be done with comprehensions:

list(map(abs, [-1,-2,-3]))    # [1, 2, 3]
[abs(i) for i in [-1,-2,-3]]  # [1, 2, 3]

Though you would need zip if you have multiple iterables:

import operator
alist = [1,2,3]
list(map(operator.add, alist, alist))  # [2, 4, 6]
[i + j for i, j in zip(alist, alist)]  # [2, 4, 6]

List comprehensions are efficient and can be faster than map in many cases, so test the times of both approaches if speed is important for you.

Still have a question about Map Function? Ask Question

Topic Outline