03 December 2022

Advantages of map function in Python

 Does Python still need the map() function?

 

In the following situation, i.e. working with multiple itarables (lists, etc.), using map function may be the best approach. It is both the most readable and the most efficient.

 ...

Above, we applied map() for a single iterable, but we can use as many of them. The function will use them based on their index, that is, first, it will call the callable for the first elements of the iterables (at index 0); then for the second; and so on.

A simple example for this:

>>> def sum_of_squares(x, y, z):
... return x**2 + y**2 + z**2
>>> x = range(5)
>>> y = [1, 1, 1, 2, 2]
>>> z = (10, 10, 5, 5, 5)
>>> SoS = map(sum_of_squares, x, y, z)
>>> list(SoS)
[101, 102, 30, 38, 45]
>>> list(map(sum_of_squares, x, x, x))
[0, 3, 12, 27, 48]
...

No comments:

Post a Comment