Python map() Function: How to use map in python ?
Tags: python, beginners, programming
Published: 2021-10-03 20:22:43

## 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 !
<br>
## 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)])
```

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.

```python
   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}")  
```
Adding the *main* method:

```python
   if __name__ == "__main__":
      for_loop()
```
We would get this output like following while the code above is run.

```
Output:
squared => [1, 4, 9, 16, 25, 36, 49, 64, 81]
```

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

```python
   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}")
```
```
Output:
squared => [1, 4, 9, 16, 25, 36, 49, 64, 81]
```

🔎🔎 ⁉️ We can also take the same result without using *for loop*, by using **map()**. The following reimplementation of the above instance.

```python
   def square(n):
       return n ** 2

   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}")
```
```
Output:
squared => [1, 4, 9, 16, 25, 36, 49, 64, 81]
```
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. 

```python
   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}")
```
```
Output:
converted list => [1, 2, 3, 4, 5, 6, 7, 8, 9]
```
Now try to convert integer to float. 
```python
   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}")
```
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()**.

```python
   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}")
```
```
Output:
abs values => [5, 2, 8, 11, 2.17, 1.99, 6, 4]
```
❓❔  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.

```python
   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}")
```
```
Output:
lambda squared => [1, 4, 9, 16, 25, 36, 49, 64, 81]
```
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**.

```python
   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)
```
```
Output:
sum of the lists => [11, 3, 2, 0, 3]
```
```python
   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}")
```
```
Output:
UPPER => ['APPLE', 'BANANA', 'GRAPE', 'MELON', 'AVOCADO', 'MANGO', 'ORANGE']

Capitalize => ['Apple', 'Banana', 'Grape', 'Melon', 'Avocado', 'Mango', 'Orange']
```
‼️ Note that you can use the functions that can get arguments as parameter like *strip()*, *split()* etc. 
```python
   s_m = ["string/", "manipulation/"]
   list_string = list(map(lambda t: t.strip("/"), s_m))
   print(f"list string => {list_string}")
```

```
Output:
list string => ['string', 'manipulation']
```
👉  Another way to manipulation list that stores string item without using lambda is *str* method.

```python
   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}")
```
```
Output: 
UPPER => ['APPLE', 'BANANA', 'GRAPE', 'MELON', 'AVOCADO', 'MANGO', 'ORANGE']

Capitalize => ['Apple', 'Banana', 'Grape', 'Melon', 'Avocado', 'Mango', 'Orange']
```

```python
   s = "string manipulation using map"
   list_split = list(map(str.split, s))
   print(f"split => {list_split}")
```
```
Output:
split => [['s'], ['t'], ['r'], ['i'], ['n'], ['g'], [], ['m'], ['a'], ['n'], ['i'], ['p'], ['u'], ['l'], ['a'], ['t'], ['i'], ['o'], ['n']]
```

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

```python
   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)
```

```
Output:
the car list => ['BMW', 'Audi', 'Bentley', 'Mercedes', 'Porsche']
```
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. 
 
```python
   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 !"
```
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.
```python
   if __name__ == "__main__":
      string = "tenet"
      p = Palindrome(string)
      print(p)
```
And the output will probably be like following:
```
Output:
The object ['t', 'e', 'n', 'e', 't'] is palindrome !
```