The map()
function in Python is a built-in function that allows you to apply a function to each element of an iterable (such as a list, tuple, or string) and return an iterable containing the results. Here is an example of how to use the map()
function:
- Define a function that you want to apply to each element of the iterable. In this example, we will use a simple function that squares a number:
def square(x):
return x**2
- Create an iterable that you want to apply the function to. In this example, we will use a list of numbers:
numbers = [1, 2, 3, 4, 5]
- Use the
map()
function to apply the function to each element of the iterable. The first argument of themap()
function is the function you want to apply, and the second argument is the iterable you want to apply the function to:
squared_numbers = map(square, numbers)
- The
map()
function returns an iterable, which can be converted to a list, tuple, or other iterable type, by using the corresponding function.
squared_numbers = list(squared_numbers)
print(squared_numbers) # Output: [1, 4, 9, 16, 25]
It’s important to note that, map()
function in Python 3 returns an iterator, which is a type of object that can be used to loop over the elements of an iterable, but not index it or slice it.
Additionally, map()
function allows passing multiple iterables and function at the same time, for instance:
first_list = [1,2,3,4]
second_list = [5,6,7,8]
def multiply(x,y):
return x*y
multiplied_list = map(multiply, first_list, second_list)
In conclusion, the map()
function in Python is a powerful and flexible tool that allows you to apply a function to each element of an iterable and return an iterable containing the results. It is easy to use and can be used to perform a wide range of operations on iterables.