The map function in Python

The built-in function map operate on lists (or similar objects called iterables). The function map takes a function and an iterable as arguments, and returns a new iterable with the function applied to each argument.


def add_some(x):
return x + 3

nums = [10, 20, 30]
result = list(map(add_some, nums))

This will add 3 to each item of the list.

The terminal output will be:

ddn_ro@linux:~/Desktop$ python
[13, 23, 33]

Of course, using lambda syntax will have the same result:

nums = [10, 20, 30]
result = list(map(lambda x: x+5, nums))

To convert the result into a list, we used list explicitly.

Leave a Reply