Python map function

Think of a situation, where you want to perform same operation on a group of objects. For eg, you want to run same commands on a family of network devices. Traditionally, to achieve this you have to iterate device objects one by one and then apply required function to run commands on devices.

In python, there is easy way to apply same function on group of objects. This is called “map” function.

Typical syntax of maps function is map(some_function, list_of_objects). “map” function will return a map type object. Which can be converted into list to pick processed objects from list.

Let us address a practical problem. Suppose you have several geometry shapes, circle, rectangle, triangle in a list like:

#Geometric objects Circle with radius 2, rectangle of 3×4, triangle of 4x5x6, last object is not covered in implementation
objlist=[[2],[3,4],[4,5,6],[4,5,6,7]]

And you are asked to calculate perimeter of these objects. To implement it, I wrote a function called “perimeter”. Depending upon number of dimensions/parameters formula is invoked to calculate perimeter of shapes.


#!/usr/local/bin/python3
import math

def perimeter(*param):
  # Unknown object
  if len(param[0]) not in [1,2,3]:
     return("Unhandled Object")
  # Circle
  if len(param[0]) == 1:
     return(2*math.pi*param[0][0])
  # Rectangle
  if len(param[0]) == 2:
     return(2*(param[0][0]+param[0][1]))
  # Triangle
  if len(param[0]) == 3:
     return(param[0][0]+param[0][1]+param[0][2])

#Geometric objects Circle with radius 2, rectangle of 3x4, triangle of 4x5x6, last object is not covered in implementation
objlist=[[2],[3,4],[4,5,6],[4,5,6,7]]

peri=map(perimeter,objlist)
# Convert map object to list and print
print(list(peri))

Output:

./maptest.py
[12.566370614359172, 14, 15, 'Unhandled Object']

First value is circumference of circle, second is perimeter of rectangle, third is perimeter of triangle and forth is an unknown object for “perimeter” function. You can extend this logic to variety of scenarios.