map() Function in Python

Python map() Function

The map() function in Python is a built-in function that applies a given function to each item in an iterable (such as a list or a tuple) and returns an iterator with the results. It takes two or more arguments: the function to apply and the iterable(s) on which the function will be applied.

The syntax for the map() function is as follows:

map(function, iterable1, iterable2, ...)

Here's a breakdown of the parameters:

  • function: This is the function that will be applied to each item in the iterable(s). It can be a built-in function, a lambda function, or a custom-defined function.
  • iterable1, iterable2, ...: These are one or more iterables (e.g., lists, tuples) on which the function will be applied. The map() function will iterate through these iterables in parallel.

The map() function returns an iterator, which can be converted to other iterable types like a list, tuple, or set using the list(), tuple(), or set() functions, respectively.

Here's an example to illustrate how map() works:

def square(x):
    return x ** 2

numbers = [1, 2, 3, 4, 5]
squared_numbers = map(square, numbers)

print(list(squared_numbers))

Output:

[1, 4, 9, 16, 25]

In this example, the map() function applies the square() function to each item in the numbers list, resulting in a new iterator containing the squared numbers. The iterator is converted to a list using the list() function for easier printing.

You can also use the map() function with multiple iterables. In that case, the provided function should accept multiple arguments:

def add(x, y):
    return x + y

numbers1 = [1, 2, 3, 4, 5]
numbers2 = [10, 20, 30, 40, 50]
added_numbers = map(add, numbers1, numbers2)

print(list(added_numbers))

Output:

[11, 22, 33, 44, 55]

In this example, the add() function takes two arguments, and the map() function applies it to corresponding pairs of items from numbers1 and numbers2, resulting in a new iterator with the sums.

The map() function provides a concise way to transform and process data in Python by applying a function to each element of an iterable or multiple iterables simultaneously.