In this article, you will learn how to use the Python map() function.
Python map() Function
The map() function in Python is a built-in function that takes in two or more arguments: a function and one or more iterables, in the form:
map(function, iterable, ...)
The function is applied to each element of the iterable(s) and a map object is returned, which can be converted into other Python objects (such as a list) if desired.
Here’s an example that uses the map() function to multiply each element of a list by 2:
def multiply(x): return x * 2 numbers = [1, 2, 3, 4] result = map(multiply, numbers) result = list(result) print(result) //[2, 4, 6, 8]
In the example, we defined the multiply function to take an argument x and return “x * 2”. Then, we created a list of numbers “[1, 2, 3, 4]” and passed it to the map() function along with the multiply function. The map() function then applies the multiply function to each element of the list “numbers” and returns a map object, which we converted to a list using the list() function and stored in the result variable.
You can also use the lambda function with map() to apply an anonymous function to each element of the iterable, like this:
numbers = [1, 2, 3, 4] result = map(lambda x: x * 2, numbers) result = list(result) print(result) //[2, 4, 6, 8]
In this example, we used a lambda function instead of the multiply function defined earlier. The lambda function takes an argument “x” and returns “x * 2”.