The map function for iterating objects in python
Let's say we have a function square for squaring numbers. And there is a list to the elements of which we need to apply this function:
def square(num):
return num ** 2
lst = [2, 3, 6, 8, 15]
In Python, to solve this problem, you can use a special function map. It takes as parameters a function and a list to which elements it should be applied. Let's use map to solve the example:
res = map(square, lst)
print(res)
Each list, like any complex object, takes up a lot of space in Python's system memory. Therefore, to save resources, after executing the code, a special iterable map object will be returned instead of a new list:
<map object at 0x000001F16674BA00>
Let's loop through it:
for el in res:
print(el)
As a result, all elements of the new list will be displayed:
4
9
36
64
225
To create a new list from a map object, you need to apply the list function to it:
lst = [2, 3, 6, 8, 15]
res = map(square, lst)
The following list will be displayed as a result:
[4, 9, 36, 64, 225]
Also, when working with the map function, you can specify a lambda function in the first parameter. Let's rewrite the previous example using a lambda function:
res = map(lambda num: num ** 2, lst, lst)
print(list(res))
Rewrite the following code using a lambda function:
def func(num):
return num + 1
lst = [1, 2, 3, 4, 5]
res = map(func, lst)
print(list(res))
Rewrite the following code using a lambda function:
def func(txt):
return txt[::-1]
lst = ['123', '456', '789']
res = map(func, lst)
print(list(res))