Let’s learn how to use the Python map function based on examples.
The syntax for the map() method is as follows:
map(function, iterable, [iterable 2, iterable 3, ...])
The map function in Python is a built-in function that allows you to apply a given function to each item in an iterable (e.g. a list, tuple, set, etc.).
Here’s an example of how to use the map function:
# Define the function to be applied def square(x): return x**2 # Define the iterable numbers = [1, 2, 3, 4, 5] # Apply the function to each item in the iterable using map squared_numbers = list(map(square, numbers)) # Print the result print(squared_numbers) # Output: [1, 4, 9, 16, 25]
In this example, the map function takes two arguments: the function to be applied (square) and the iterable (numbers). The map function returns a map object, which can be converted to a list (as shown in this example) or any other iterable. The square function is applied to each item in the numbers list, and the result is stored in the squared_numbers list.