|

# Higher Order map() Function In Python A useful higher-order function you can make use of in Python is the map() function. A higher-order function takes a function and a set of data values as arguments. The function which you pass in is applied to each data value, and a set of results or a single data value is returned. The purpose of a higher-order function is to make it easy to apply an operation to many different data elements. In this tutorial, we’ll look at several examples of how to use Python’s map() function to apply a mapping using lists, tuples, and strings.

## map() Basics

We can begin with a very simple list of numbers represented as strings. The list has three items, each being a string.

``string_numbers = ['1', '2', '3']``

Our goal is to convert every string in the list into an actual number. We know that Python has a built-in int() function that can do just that. To apply the int() function to all items in this list, we can use the map() function. So notice that we pass the int() function as the first argument to map(). Also notice that we are passing `int` as a first-class object without calling the function with the () parenthesis. The second argument is iterable which contains all of the elements for the function to be applied to.

``````string_numbers = ['1', '2', '3']
result = map(int, string_numbers)

print(result)
``````
`<map object at 0x000001E878B6FB20>`

The map() function builds and returns a new map object as we can see from the output above. In order to get at the actual data, we can pass that map object into either the list() or tuple() functions like so.

``````string_numbers = ['1', '2', '3']
result = map(int, string_numbers)
result = list(result)

print(result)``````
`[1, 2, 3]`
``````string_numbers = ['1', '2', '3']
result = map(int, string_numbers)
result = tuple(result)

print(result)``````
`(1, 2, 3)`

## Custom Function With map()

The neat thing about map() is that you can define your own function which can do whatever you like. Then, when you call the map() function, you can again pass your own function as the first argument. In this next example, we first define a function that checks for the letter ‘a’ in a string. If it finds a letter ‘a’, then it capitalizes it. We’ll use that custom function along with the map() function on a string to see how it works.

``````def a_checker(str):
if 'a' in str:
return 'a'.capitalize()
else:
return str

print(list(result))``````
`['A', 'b', 'r', 'A', 'c', 'A', 'd', 'A', 'b', 'r', 'A']`

## Custom Function Example Two

Let’s write another function that we can use with map(). We want to output the type of any object contained in a list. So inside of our custom function, we can call the type() function. Then we construct a list that holds all kinds of different Python types. When we call the map() function and pass it our custom function, it will print out all of those types for us.

``````def type_checker(var):
print(type(var))

random = ['hi', 7, 3.14, True, [1, 2], ('one', 'two'), {'key': 'val'}]

result = map(type_checker, random)

list(result)``````
```<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>
<class 'list'>
<class 'tuple'>
<class 'dict'>```

## Using print() with map()

print() is probably the most used function in the Python language. Can we use it with map()? We sure can.

``````random = ['hi', 7, 3.14, True, [1, 2], ('one', 'two'), {'key': 'val'}]

result = map(print, random)

list(result)``````
```hi
7
3.14
True
[1, 2]
('one', 'two')
{'key': 'val'}```

## Neat Tricks With map()

``````def dash_printr(num):
print('-' * num)

num_dashes = [20, 15, 10, 5, 1, 5, 10, 15, 20]

result = map(dash_printr, num_dashes)

list(result)``````
```--------------------
---------------
----------
-----
-
-----
----------
---------------
--------------------```

## Using lambda With map()

Another approach you can use with the map() function is to pass a lambda function as the first argument. A lambda function is a single-line function declared with no name, which can have any number of arguments, but it can only have one expression. People either love em, or hate em, but either way, you can use them if you like, so we demonstrate that here.

``````numbers = [1, 3, 7, 9, 11]

result = map(lambda num: num * 5, numbers)

print(list(result))``````
`[5, 15, 35, 45, 55]`
``````dogs = ['Charlie', 'Winnie', 'Mosely', 'Bella', 'Mugsy']

a_count = map(lambda word: word.count("a"), dogs)

print(list(a_count))``````
`[1, 0, 0, 1, 0]`
``````dogs = ['Charlie', 'Winnie', 'Mosely', 'Bella', 'Mugsy']

dog_bling = map(lambda val: val.replace("s", "\$"), dogs)

print(list(dog_bling))``````
`['Charlie', 'Winnie', 'Mo\$ely', 'Bella', 'Mug\$y']`

### Higher Order map() Function In Python Summary

• applies a function to each value in a sequence (such as a list, a tuple, or a string)
• returns a new sequence of the results
• the map() function builds and returns a new map object
• map object is usually passed to list() function
• can be used to replace for loops
• map object can be passed directly to another map function to perform further transformations of the data
• can use built-in, custom, or lamda functions as the first argument
|