The map() function takes two arguments: a function and an iterable (such as a list, tuple, or string).
It applies the function to each element of the iterable and returns a new iterable with the transformed values.
Syntax
map(function, iterable)
Let's say we have a list of numbers, and we want to square each number in the list. Instead of writing a loop to iterate through the list and square each number, we can simply use the map() function to achieve the same result in a more concise way.
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x**2, numbers))
print(squared_numbers)
Output
[1, 4, 9, 16, 25]
Here, we passed a lambda function (a small anonymous function) as the first argument to map(). This lambda function takes a single argument x and returns the square of that number. The map() function applies this lambda function to each element in the numbers list and returns a new iterable, which we convert into a list using the list() function.
Using the map() function, we can perform a wide range of operations on each element of an iterable. It can be used with built-in functions like len(), str(), int(), as well as user-defined functions.
Benefits of using the map() function
We can eliminate the need for explicit loops, resulting in shorter and more readable code.
The map() function performs operations on each element of an iterable in parallel, making it more efficient than using a traditional for loop.
Code reusability: The map() function allows us to pass any function as an argument, making our code more flexible and reusable.
No comments:
Post a Comment