Python Language Mapping values of different iterables

Download Python Language for free

Example

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]
    
Series and Parallel Mapping