Avatar

Blogging tips

Avatar

Python, Django and Flask

Avatar

Latest tech posts

Monday, February 10, 2020

Map function in python [map()]

       Map function is a good alternative for the “for loops” in python. Sometimes we do not want our code to look clumsy because of all the for loops we have used. In this case the “map()” in python comes to the rescue.

What are map functions?

map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.)



Syntax

map(fun, iter)


map() Parameter
  1. function - map() passes each item of the iterable to this function.
  2. iterable iterable which is to be mapped

You can pass more than one iterable to the map() function.

The map() function applies a given to function to each item of an iterable and returns a list of the results.

The returned value from map() (map object) then can be passed to functions like list() (to create a list), set() (to create a set) and so on.


Map function with a list

In this example there is a single list called numbers and a function square. The map function iterates the list one by one, passes the value to the function, gets the returned value and stores it in a map object. This can be converted to a list or tuple later.



Map function with a lambda function

This example is also similar to the previous one. But instead of passing the value to a separate function we are using the lambda function inline.



Map function with multiple lists or iterables

This example has two lists. The map function iterates both the list and adds them. I,e it adds the first value of the first list with the first value of the second list and so on.
(li1[0] + li2[0]) + (li2[1] + li2[1]) + (li3[2] + li3[2]) + …….



Scenarios where map function can be used.

  1. Given a list find the square of all the numbers in the list
  2. Check if the values of the list are “odd” or “even” etc



No comments:

Post a Comment