The map() function applies a given to function to each item of an iterable and returns a list of the results.
The returned value from map() (map object) then can be passed to functions like list() (to create a list), set() (to create a set) and so on.
Example 1: How map() works?
def calculateSquare(n):
return n*n
numbers = (1, 2, 3, 4)
result = map(calculateSquare, numbers)
print(result)
# converting map object to set
numbersSquare = set(result)
print(numbersSquare)
When you run the program, the output will be:
<map object at 0x7f722da129e8>
{16, 1, 4, 9}
The map() function executes a specified function for each item in a iterable. The item is sent to the function as a parameter.
map(function, iterables)
Map applies a function to all the items in an input_list.
Most of the times we want to pass all the list elements to a function one-by-one and then collect the output. For instance:
items = [1, 2, 3, 4, 5]
squared = []
for i in items:
squared.append(i**2)
Map allows us to implement this in a much simpler and nicer way. Here you go:
items = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, items))
map isn't particularly pythonic. I would recommend using list comprehensions instead:
map(f, iterable)
is basically equivalent to:
[f(x) for x in iterable]
map on its own can't do a Cartesian product, because the length of its output list is always the same as its input list. You can trivially do a Cartesian product with a list comprehension though:
[(a, b) for a in iterable_a for b in iterable_b]
The syntax is a little confusing -- that's basically equivalent to:
result = []
for a in iterable_a:
for b in iterable_b:
result.append((a, b))