Python built-in Method - map()

https://‮gi.www‬iftidea.com

In Python, the map() function is a built-in method that applies a given function to each item of an iterable and returns a new iterable with the results.

The syntax for map() is as follows:

map(function, iterable)

Here, function is the function to be applied to each item in the iterable, and iterable is the iterable object that we want to apply the function to.

For example:

def square(x):
    return x ** 2

my_list = [1, 2, 3, 4, 5]
squared_list = list(map(square, my_list))
print(squared_list)    # [1, 4, 9, 16, 25]

In the example above, we define a function square() that squares its input, and then use the map() function to apply it to each item in the list my_list. We convert the resulting map object into a list using the list() function, and then print it out.

The map() function is useful when you want to apply a function to each item in an iterable and create a new iterable with the results. It is often used in conjunction with lambda functions, which are small, anonymous functions that can be defined on the fly.

Note that the map() function returns an iterable, not a list. To get a list, you need to convert the iterable to a list using the list() function. Also note that the map() function stops when any of the iterables are exhausted, so the length of the resulting iterable may be shorter than the original iterable. If you want to ensure that the resulting iterable has the same length as the original iterable, you can use the itertools.zip_longest() function.