It is common to have to work with list or iterable by manipulating the values of their elements. Usually, this is done by using a for loop or a list comprehension but
Python allows the user to do that using a mapping technique via the built-in function map().
The syntax is
map(function, iterable)
This function can be useful in a variety of situations, including
- transforming data
- performing calculation
- combining multiple iterables.
Following we'll see some, very, simple examples.
Transforming data
You can use it to uppercase a string or convert a list of integer in string format into int type.
Example 1
def upper_char(char: str):
return char.upper()
lower_str = 'hello world'
print("".join(map(upper_char, lower_str)))
# 'HELLO WORLD'
Example 2
input_str = ['1', '2', '3', '4']
input_int = list(map(int, input_str))
print(input_int)
# [1, 2, 3, 4]
The last one can be usefull when you have to parse a numeric input read from a file or stdin (standard input). I.e. if you have tried to solve AoC (Adventure of Code) exercises you have to parse a file and convert data from string to int.
Performing calculation
Calculate the square value for each element of a list of int.
def square(x):
return x*x
data = [1, 2, 3, 4]
print(list(map(square, data)))
# [1, 4, 9, 16]
Combining multiple iterables
map() can be used to apply a function to corresponding elements of multiple iterables.
In fact the real syntax is
map(function, iterable, *iterables)
As you can see it can accept more than one iterable and in that case, it pass a single item for each iterator to the function in parallel.
For example, you can use map() to add corresponding elements of two lists together, or perform other types of operations on multiple iterables.
def add_elements(x, y):
return x + y
list_1 = [1, 3, 5, 7]
list_2 = [2, 4, 6, 8]
print(list(map(add_elements, list_1, list_2)))
# [3, 7, 11, 15]
If more iterables are passed to map() it stops when the shortest iterable is exhausted.
Conclusion
In summary, the map() function is a useful tool for manipulating data. By allowing you to apply a function to each element of an iterable, it enables you to make transformations, perform calculations, and combine multiple iterables in a concise and efficient manner. This versatility makes it a valuable tool.