Site icon DesignLinux

Python map() Function

map() is a built-in function in Python that applies a function to all elements in a given iterable. It allows you to write simple and clean code without using loops.

Python map() Function

The map() function takes the following form:

map(function, iterable, ...)

It accepts two mandatory arguments:

In Python 3, map() returns a map object with a size equal to the passed iterable object. In python 2 the function returns a list.

Let’s take a look at an example to explain better how the map() function works. Say we have a list of strings, and we would like to convert each element in the list into uppercase.

One way to do this is to use the traditional for loop:

directions = ["north", "east", "south", "west"]
directions_upper = []

for direction in directions:
    d = direction.upper()
    directions_upper.append(d)

print(directions_upper)
['NORTH', 'EAST', 'SOUTH', 'WEST']

With map() function, the code will be much simpler and more flexible.

def to_upper_case(s):
    return s.upper()

directions = ["north", "east", "south", "west"]

directions_upper = map(to_upper_case, directions)

print(list(directions_upper))

We’re using the list() function to convert the returned map object into a list:

['NORTH', 'EAST', 'SOUTH', 'WEST']

If the callback function is simple, the more Pythonic way is to use a lambda function:

directions = ["north", "east", "south", "west"]

directions_upper = map(lambda s: s.upper(), directions)

print(list(directions_upper))
A lambda function is a small anonymous function.

Here is another example showing how to create a list of square numbers from 1 to 10:

squares = map(lambda n: n*n , range(1, 11))
print(list(squares))
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
The range() function generates a sequence of integers.

Using map() with Multiple Iterables

You can pass as many iterables as you want to the map() function. The number of required input arguments that the callback function accepts must be the same as the number of the iterables.

The following example shows how to perform element-wise multiplication on two lists:

def multiply(x, y):
  return x * y

a = [1, 4, 6]
b = [2, 3, 5]

result = map(multiply, a, b)

print(list(result))
[2, 12, 30]

The same code, but using lambda function will look this way:

a = [1, 4, 6]
b = [2, 3, 5]

result = map(lambda x, y: x*y, a, b)

print(list(result))

When multiple iterables are provided, the size of the returned object is equal to the shortest iterable.

Let’s see an example when the iterables are not of the same length:

a = [1, 4, 6]
b = [2, 3, 5, 7, 8]

result = map(lambda x, y: x*y, a, b)

print(list(result))

The excess elements (7 and 8) are ignored:

[2, 12, 30]

Conclusion

The Python’s map() function takes an iterable object, along with a function and applies that function to each element in the iterable.

If you have any questions or feedback, feel free to leave a comment.

python
Exit mobile version