Skip to content

[Python] Use map() function to iterate the parameter list to a function

Last Updated on 2021-08-03 by Clay

The use of map() function in Python is very simple, so simple that it hardly needs any explanation. However, the map() function is still used in many places, so it is still slightly recorded.


How to use map() function

The way to use map() is basically map(function, iterable_list). function enters the function we want to use iterabel_list enters the objects we want to iterate over, such as a List.

By the way, map() returns an iterable category in Python3. Let’s look at a simple sample code:

def add(x):
    return x+1

input = [1, 2, 3, 4, 5]
output = map(add, input)
print(output)



Output:

<map object at 0x00000228D75E96A0>

As you can see, what we first input in map() is the add() function we defined first, and then input the array of [1, 5]. But the result returned is the end is an iterable object. For this, we may need to convert it into a List data type.

def add(x):
    return x+1

input = [1, 2, 3, 4, 5]
output = list(map(add, input))
print(output)



Output:

[2, 3, 4, 5, 6]

We can see the result of add() returned by map() this time. In addition, it is quite common to use the lambda anonymous function with map().

input = [1, 2, 3, 4, 5]
output = list(map(lambda x: x+1, input))
print(output)



Output:

[2, 3, 4, 5, 6]

We can see the same result. So the above is how to use the map() function in Python.


References


Read More

Tags:

Leave a ReplyCancel reply

Exit mobile version