Python How to call a function for all elements of a list by using map

eye-catch Python

If a function needs to be processed for all elements of a list, map function can be used.

Sponsored links

Basic usage of map function

map function requires a function for the first argument and iterable objects for the second and later arguments.

map(function, iterable1, iterable2, ...)

The number of the iterable object needs to be the same as the number of the argument of the function specified in the first argument.

Let’s see the following example. It calculates the square value for all the elements.

def square(val):
    return val * val


result = map(square, [1, 2, 3])
print(result)
# <map object at 0x00000174CF1D5FA0>
print([print(v) for v in result])
# 1
# 4
# 9
# [None, None, None]
print(list(result))  # []

As you can see, the map object can be used in a for-loop but the last element is weird.

Note that list(result) becomes empty if it is used in a for-loop in advance.

Check this article if you first see this syntax [v for v in list_value]

Sponsored links

Convert map object to list

In a production code, a map object should be converted to a list for usability.

result = map(square, [1, 2, 3])
print(f"list(result): {list(result)}")
# list(result): [1, 4, 9]

We don’t have to separate the line. Let’s write it in this way below.

result = list(map(square, [1, 2, 3]))
result = list(map(square, [1, 2, 3]))
[print(v) for v in result]
# 1
# 4
# 9

The weird element [None, None, None] is not shown here.

Convert map object to set to remove duplicates

If duplicates need to be removed from the result, set should be used.

print(list(map(square, [1, 2, 3, 1, 2, 3, 4])))
# [1, 4, 9, 1, 4, 9, 16]
print(set(map(square, [1, 2, 3, 1, 2, 3, 4])))
# {16, 1, 4, 9}

set class removes the duplicates while list class keeps all the results.

Passing multiple iterable objects

It’s possible to pass multiple iterable objects if the specified function has 2 or more arguments.

def multiply(val, val2):
    return val * val2


result = map(multiply, [1, 2, 3, 4], [2, 3, 4, 5])
print(list(result))  # [2, 6, 12, 20]

If the number of the elements is not the same, the number of the results matches the less number of the elements.

result = map(multiply, [1, 2, 3, 4], [1, 1])
print(list(result))  # [1, 2]

Using lambda function in map function

The first argument is a function. Therefore, it’s also possible to use the lambda function there.

print(list(map(lambda val: val * val, [1, 2, 3])))
# [1, 4, 9]

This is the same logic as square function defined above.

Comments

Copied title and URL