map() is a built-in function in Python that takes a function and one or more iterables as input, returning a new iterable where each element is the result of applying the input function to the corresponding elements.
Function Syntax
map(function, iterable, ...)
Parameters:
function: A function that takes elements from each iterable passed tomap()as input and returns the transformed result.iterable: Iterable objects (can be multiple); elements from each object are passed as input to thefunction.
The map() function returns a new iterable object.
map() Function Examples
Here's an example demonstrating how to use the map() function to square all elements in a list:
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]
Convert string numbers in a list to floating-point numbers:
my_list = ["0.1", "1.2", 2.3, "3.4", 5]
# Use built-in float function
float_list = list(map(float, my_list))
print(float_list) # [0.1, 1.2, 2.3, 3.4, 5.0]
Handle multiple iterable objects:
lst1 = [1, 2, 3]
lst2 = [4, 5, 6]
# x, y from elements of two iterables respectively
def handle(x, y):
return x * y
result = list(map(handle, lst1, lst2))
print(result) # [4, 10, 18]