map(): applying a function to each item in an iterable in Python

The map() function applies a function to each item in an iterable.

Dictionaries, lists, and tuples are examples of iterables.

The first argument is the function name, the second argument is the iterable.

Let’s calculate the cubic of each number in the list.

def cubic(number):
    return number**3

numbers = [2, 5, 10]

numbers_cubics = map(cubic, numbers)

print(numbers_cubics)

print(list(numbers_cubics))
<map object at 0x105669760>

[8, 125, 1000]

Notice that map() returns a map object, so you have to convert it to a list or tuple, for instance, to print the results.

I recommend learning about Python Lambda Functions to see map() applied in another way.

Watch on Youtube

You can also watch this content on Youtube: