Mapping values of different iterables
suggest changeFor example, combining each i-th element of multiple iterables:
There are different requirements if more than one iterable is passed to map:
- 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
- The mapping stops when the shortest iterable is exhausted. Since Python 3.14,
strict=TrueraisesValueErrorwhen the lengths differ. In Python 2,mapkept going and filled inNonefor finished iterables;itertools.imapstopped early and was removed in Python 3:
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]
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents