The map() function in Python is used to apply a function to each element in an iterable (such as a list, tuple, or string) and return a new iterable with the results. It takes two arguments: a function and an iterable.
.jpg)
The general syntax of the map() function is as follows:
map(function, iterable)
Here, function is a function that takes one argument and returns a value, and iterable is the iterable being mapped over.
For example, the following code uses the map() function to square each number in a list:
numbers = [1, 2, 3, 4, 5] squares = map(lambda x: x**2, numbers) print(list(squares)) # Output: [1, 4, 9, 16, 25]
In this example, the lambda function lambda x: x**2 squares each number in the numbers list, and the map() function applies this function to each element in the list.
The map() function is useful for applying a transformation to each element in an iterable in a concise and readable way. It can be used with any iterable that supports iteration, and can also be used with built-in functions like len() and str().
0 Comments