Develop myMap Function¶
Develop a function by name myMap
which takes a collection and a function as arguments. myMap
function should do the following:
- Iterate through elements.
- Apply the transformation logic using the argument passed. Append the transformed record to the list.
- Return the collection with all the elements which are transformed based on the logic passed.
- We will also validate the function using a simple list of integers.
{note}
`map` is typically used to perform row level transformations. It means we will apply transformation rule on each and every element in the iterable or collection. The number of elements in input collection and output collection will always be same.
myMap
function using conventional loops.
In [1]:
def myMap(c, f):
c_t = []
for e in c:
c_t.append(f(e))
return c_t
In [2]:
l = list(range(1, 10))
l
Out[2]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
In [3]:
myMap(l, lambda e: e * e)
Out[3]:
[1, 4, 9, 16, 25, 36, 49, 64, 81]
myMap
function using list comprehensions.
In [4]:
def myMap(c, f):
return [f(e) for e in c]
In [5]:
l = list(range(1, 10))
l
Out[5]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
In [6]:
myMap(l, lambda e: e * e)
Out[6]:
[1, 4, 9, 16, 25, 36, 49, 64, 81]