-->

how to use "map" keyword or function in python?

  • "map' is a built-in function in python.
  • It takes first argument as a function or a callable  object.
  • All other arguments must be sequence of elements otherwise it raises an error.
  • we can reduce the number of lines code using map.
  • It's like functional programming technique.
  • map return a list of the results of applying the function to the items of the argument sequence(s).
  •  If more than one sequence is given, the function is called with an argument list consisting of the corresponding item of each sequence, substituting 'None' for missing values when not all sequences have the same length.

Convert list of numbers to list of strings without using map

l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
output = []
for i in l:
output.append(str(i))
print(output)
# Output: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

Convert list of numbers to list of strings using map

# I love to use it
l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
output = map(str, l)
print(output)
# Output: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

Return list of elements by adding numbers of two lists based on their indexes - Traditional way

l1 = [1, 2, 3, 4, 5, 6]
l2 = [10, 20, 30, 40, 50, 60]
output = []
for i, j in zip(l1, l2):
output.append(i+j)
print(output)
# Output: [11, 22, 33, 44, 55, 66]

Return list of elements by adding numbers of two lists based on their indexes - Functional Programming

l1 = [1, 2, 3, 4, 5, 6]
l2 = [10, 20, 30, 40, 50, 60]
def sum_elements(a, b):
return a + b
output = map(sum_elements, l1, l2)
print(output)
# Output: [11, 22, 33, 44, 55, 66]

Let's test the map with different types of inputs

how to use multiple arguments with "map" python?

def function(*args):
return args
output = map(function, [1,2,3], ("a", "b", "c"), (1.2, 2.3, 3.4))
print(output)
# Output: [(1, 'a', 1.2), (2, 'b', 2.3), (3, 'c', 3.4)]

how to use multiple arguments of varying length with "map" with python?

def function(*args):
return args
output = map(function, [1,2,3], ("a", "b", "c", "d", "e", "f"), (1.2, 2.3, 3.4))
print(output)
# Output: [(1, 'a', 1.2), (2, 'b', 2.3), (3, 'c', 3.4), (None, 'd', None), (None, 'e', None), (None, 'f', None)]

use "None" instead of function with "map" in python

output = map(None, [1,2,3], ("a", "b", "c"), (1.2, 2.3, 3.4))
print(output)
# Output: [(1, 'a', 1.2), (2, 'b', 2.3), (3, 'c', 3.4)]

use other data types like "list" instead of function with "map" in python

output = map([], [1,2,3], ("a", "b", "c"), (1.2, 2.3, 3.4))
# Output: TypeError: 'list' object is not callable

Buy a product to Support me