Python Map() Function

The map() function is used to process a function for each item of an iterable and returns an iterator.

In the map() function, each value of iterators is mapped to a function parameter and executes the function, returning an iterator object.

So, without using a loop, we can execute a function for each item of the iterator.

Syntax

map(<Function_Name>, <Iterable_Object>)

Function_Name

The function to execute for each item.

Iterable_Object

It is iterable which is to be mapped.

Example

values = [10, 20, 30]

def Add(values):
    return values + 10

result = map(Add, values)

print(list(values))
print(list(result))

Output

[10, 20, 30]

[20, 30, 40]

In above example you see first output is original list and second output is after map function. In function, we have added 10 to each item.

map() function using lambda

A lambda function is a short function without a name.

Example

values = [10, 20, 30]

result = map(lambda val: val+10, values)

print(list(values))
print(list(result))

Output

[10, 20, 30]

[20, 30, 40]

Summary

map() function that works as an iterator to return a result after applying a function to every item of an iterable.


Similar Articles