Programming Language/Python
[built-in] map()
sohyxxnz
2022. 8. 25. 22:45
Built-in Functions
The Python interpreter has a number of functions and types built into it that are always available. They are listed [here](https://docs.python.org/3/library/functions.html#built-in-functions) in alphabetical order.
map()
Return an iterator that applies function to every item of iterable, yielding the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted.
# map(function, iterable, ...)
# return double of n
def addition(n):
return n + n
# double all numbers using map()
numbers = (1, 2, 3, 4)
result = map(addition, numbers)
print(list(result)) # [2, 4, 6, 8]
# double all numbers using map and lambda
numbers = (1, 2, 3, 4)
result = map(lambda x: x + x, numbers)
print(list(result)) # [2, 4, 6, 8]
# add two lists using map and lambda
numbers1 = [1, 2, 3]
numbers2 = [4, 5, 6]
result = map(lambda x, y: x + y, numbers1, numbers2)
print(list(result)) # [5, 7, 9]
# map() can listify the list of strings individually
l = ['sat', 'bat', 'cat', 'mat']
test = list(map(list, l))
print(test) # [['s', 'a', 't'], ['b', 'a', 't'], ['c', 'a', 't'], ['m', 'a', 't']]
# make strings and numbers to iterable objects
list(map(int, ['1', '2', '3', 4.5, 5.8])) # [1, 2, 3, 4, 5]
# map object is not subscriptable
ten_times = map(lambda x: 10 * x, (1, 2, 3, 4, 5)
ten_times[0] # TypeError: 'map' object is not subscriptable
Reference
[python docs] (https://docs.python.org/3/library/functions.html#map)
[geeksforgeeks] (https://www.geeksforgeeks.org/python-map-function/)
[realpython] (https://realpython.com/python-map-function/)