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.

Example:

def add_some(x):
return x + 3

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

This will add 3 to each item of the list.

The terminal output will be:

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

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

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

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

Leave a Reply