DEV Community

Cover image for Python map() Function: How to use map in python ?
Enes Karata┼č
Enes Karata┼č

Posted on

Python map() Function: How to use map in python ?

Python map() Function : How to work ?

­čôŹ Hello everyone in this tutorial we are going to investigate map() function in python together. Firstly we are going to start with what map() is.
­čĹë The map() function is used for doing some process with all the items in an iterable(list, tuple etc.) without using a loop. When you need to apply given function to each item in an iterable the map() can be pretty useful. Alright let's go ahead the next step !

Getting started with map() function

Sometimes you might want to apply process to all the items of an iterable. The most common approach to do that is using for loop in python. However we are going to handle this situation without using loop. So, this way is map().

Before using the map() function we don't need to import any module so, to be able to use the map() you need to use just directly in python file that's sufficient.
The syntax of the map() function as the following:

map(function, iterable[...iterable(N)])
Enter fullscreen mode Exit fullscreen mode

Let us begin with the most common example. Suppose you have a list and you want to transform square the each item of iterable. You would probably think using for loop as the first like below.

   def for_loop():
      number_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
      square_list = []
      for number in number_list:
         square_list.append(number ** 2)
      print(f"squared => {square_list}")  
Enter fullscreen mode Exit fullscreen mode

Adding the main method:

   if __name__ == "__main__":
      for_loop()
Enter fullscreen mode Exit fullscreen mode

We would get this output like following while the code above is run.

Output:
squared => [1, 4, 9, 16, 25, 36, 49, 64, 81]
Enter fullscreen mode Exit fullscreen mode

Alright! Let us code the better one. We are going to code again for loop as single line.

   def loop_fun():
      number_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
      square_list = [number**2 for number in number_list]
      print(f"squared => {square_list}")
Enter fullscreen mode Exit fullscreen mode
Output:
squared => [1, 4, 9, 16, 25, 36, 49, 64, 81]
Enter fullscreen mode Exit fullscreen mode

­čöÄ­čöÄ Ôüë´ŞĆ We can also take the same result without using for loop, by using map(). The following reimplementation of the above instance.

   def map_fun():
      list_number = [1, 2, 3, 4, 5, 6, 7, 8, 9]
      square_list =  list(map(square, list_number))
      print(f"squared => {square_list}")
Enter fullscreen mode Exit fullscreen mode
Output:
squared => [1, 4, 9, 16, 25, 36, 49, 64, 81]
Enter fullscreen mode Exit fullscreen mode

Take a look at the result that's exactly the same with for loop. The square_list gives us the transformation each items of the list_number. Firstly we've implemented the classic for loop method and so changed a bit. And then we put for loop inside of the list, it is about code optimization. And the last we've used the map() function instead of for loop.

­čĹë So far so good ! And of course not finished yet so we are about to move on the other implementations of map().

ÔÇ╝´ŞĆ The map() allows the type conversion for instance suppose you have a list that stores string characters. You're also able to type conversion on all items of the list using the map() function.

   def map_fun():
      list_string = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
      list_int = list(map(int, list_string))
      print(f"converted list => {list_int}")
Enter fullscreen mode Exit fullscreen mode
Output:
converted list => [1, 2, 3, 4, 5, 6, 7, 8, 9]
Enter fullscreen mode Exit fullscreen mode

Now try to convert integer to float.

   def map_fun():
      list_int = [1, 2, 3, 4, 5, 6, 7, 8, 9]
      list_float = list(map(float, list_int))
      print(f"converted list => {list_float}")
Enter fullscreen mode Exit fullscreen mode

In the code above we have passed the type as parameter to the map() so the type of all items has changed.

Let us continue to the instances. In the next one we are going to use another callable method in the map(). There are some built-in functions that you can use in the map().

   def map_fun():
      list_numbers = [-5, 2, -8, 11, -2.17, -1.99, 6, 4]
      abs_list = list(map(abs, list_numbers))
      print(f"abs values => {abs_list}")
Enter fullscreen mode Exit fullscreen mode
Output:
abs values => [5, 2, 8, 11, 2.17, 1.99, 6, 4]
Enter fullscreen mode Exit fullscreen mode

ÔŁôÔŁö What if we try to use lambda in the map function.­čĄö Of course we do! Go back above the 'square' example and implement the lambda expression like following.

   def map_fun():
      number_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
      list_square = list(map(lambda number: number ** 2, number_list))
      print(f"lambda squared => {list_square}")
Enter fullscreen mode Exit fullscreen mode
Output:
lambda squared => [1, 4, 9, 16, 25, 36, 49, 64, 81]
Enter fullscreen mode Exit fullscreen mode

Yes, It works ÔÇ╝´ŞĆ
Let's show how useful method lambda is by one more example. Sometimes we need to do some process like addition, substruction etc. between two lists. In those times we can just use the map() with lambda.

   def map_fun():
      list_num_1 = [8, 4, -7, 3, -2]
      list_num_2 = [3, -1, 9, -3, 5]

      list_sum = list(map(lambda t1, t2: t1+t2, list_num_1, list_num_2))
      print(list_sum)
Enter fullscreen mode Exit fullscreen mode
Output:
sum of the lists => [11, 3, 2, 0, 3]
Enter fullscreen mode Exit fullscreen mode
   def map_fun():
     fruits = ["apple", "banana", "grape", "melon", "avocado", "mango", "orange"]
     upper_fruits = list(map(lambda fruit: fruit.upper(), fruits))
     capitalize_fruits = list(map(lambda fruit: fruit.capitalize(), fruits))
     print(f"UPPER => {upper_fruits}")
     print(f"Capitalize => {capitalize_fruits}")
Enter fullscreen mode Exit fullscreen mode
Output:
UPPER => ['APPLE', 'BANANA', 'GRAPE', 'MELON', 'AVOCADO', 'MANGO', 'ORANGE']

Capitalize => ['Apple', 'Banana', 'Grape', 'Melon', 'Avocado', 'Mango', 'Orange']
Enter fullscreen mode Exit fullscreen mode

ÔÇ╝´ŞĆ Note that you can use the functions that can get arguments as parameter like strip(), split() etc.

   s_m = ["string/", "manipulation/"]
   list_string = list(map(lambda t: t.strip("/"), s_m))
   print(f"list string => {list_string}")
Enter fullscreen mode Exit fullscreen mode
Output:
list string => ['string', 'manipulation']
Enter fullscreen mode Exit fullscreen mode

­čĹë Another way to manipulation list that stores string item without using lambda is str method.

   fruits = ["apple", "banana", "grape", "melon", "avocado", "mango", "orange"]
   upper_fruits = list(map(str.upper, fruits))
   capitalize_fruits = list(map(str.capitalize, fruits))

   print(f"UPPER => {upper_fruits}\nCapitalize => {capitalize_fruits}")
Enter fullscreen mode Exit fullscreen mode
Output: 
UPPER => ['APPLE', 'BANANA', 'GRAPE', 'MELON', 'AVOCADO', 'MANGO', 'ORANGE']

Capitalize => ['Apple', 'Banana', 'Grape', 'Melon', 'Avocado', 'Mango', 'Orange']
Enter fullscreen mode Exit fullscreen mode
   s = "string manipulation using map"
   list_split = list(map(str.split, s))
   print(f"split => {list_split}")
Enter fullscreen mode Exit fullscreen mode
Output:
split => [['s'], ['t'], ['r'], ['i'], ['n'], ['g'], [], ['m'], ['a'], ['n'], ['i'], ['p'], ['u'], ['l'], ['a'], ['t'], ['i'], ['o'], ['n']]
Enter fullscreen mode Exit fullscreen mode

On the other hand the lambda can be quite useful about dictionaries in the map().

   def map_fun():
      car_trademarks = {
          "car1": "BMW",
          "car2": "Audi",
          "car3": "Bentley",
          "car4": "Mercedes",
          "car5": "Porsche"
          }
      trademarks_list = list(map(lambda index: car_trademarks.get(index), car_trademarks))
      print(trademarks_list)
Enter fullscreen mode Exit fullscreen mode
Output:
the car list => ['BMW', 'Audi', 'Bentley', 'Mercedes', 'Porsche']
Enter fullscreen mode Exit fullscreen mode

Alright ! The last we are going to write our own module using OOP approach. The module returns string message containing information about given string whether palindrome is or not.

   class Palindrome(object):
      def __init__(self, str_obj):
          self.list_obj = list(map(lambda t: t.strip(), str(str_obj)))

      def _isPalindrome(self):
          list_temp = self.list_obj
          list_temp = list_temp[::-1]
          if list_temp == self.list_obj:
              return True
          return False

      def __str__(self):
          if self._isPalindrome():
              return f"The object {self.list_obj} is palindrome !"
          else:
              return f"The object {self.list_obj} is not palindrome !"
Enter fullscreen mode Exit fullscreen mode

The class takes single string argument and compare with its reverse using list. If it's the same this is palindrome, if it's not the same this is not palindrome.
­čĹë Adding the main method to run the class Palindrome.

   if __name__ == "__main__":
      string = "tenet"
      p = Palindrome(string)
      print(p)
Enter fullscreen mode Exit fullscreen mode

And the output will probably be like following:

Output:
The object ['t', 'e', 'n', 'e', 't'] is palindrome !
Enter fullscreen mode Exit fullscreen mode

Discussion (6)

Collapse
xtofl profile image
xtofl

Thanks for marketing map. Yes, map rocks. It is very idiomatic, for decades now, so I wish people stopped teaching for-loops to new programmers. Loops make messy code, really, that hides the intent in favor of showing the mechanism. They are not 'classic' but 'outdated' (in 90% of the cases).

Also, I would love if exemplary articles as this one would choose tuple in their examples. Especially in the context of map, lists are really overkill.

I want to pont to a recent article of mine that explains this:
dev.to/xtofl/tuple-reveals-your-in...

Collapse
bl4ckst0n3 profile image
Enes Karata┼č Author

thanks for the response ! :)

Collapse
suyogwani11 profile image
Suyog Wani • Edited on

Nice article.

  trademarks_list = list(map(lambda index: car_trademarks.get(index), car_trademarks))
Enter fullscreen mode Exit fullscreen mode

can be simplified to

  trademarks_list = list(map(car_trademarks.get, car_trademarks))
Enter fullscreen mode Exit fullscreen mode
Collapse
bl4ckst0n3 profile image
Enes Karata┼č Author

i justed wanted to show how to use by lambda so that I've used lambda in this line

Collapse
bl4ckst0n3 profile image
Enes Karata┼č Author

thank you so much for this response :)

Collapse
ughurh profile image
Ughur Huseyn

map/filter/reduce are all the reason I like functional programming