The map()
function applies a given function to each item of an iterable object. It returns an iterator object containing the transformed element as per the given function.
map(key, iterable)
copy
key |
A required argument that specifies the function that will be applied to all the elements of the iterable. |
iterable |
The iterable whose each element will be passed to the key function. |
The map()
function returns a map object containing the return values by the function after being applied to each item of the iterable. The map object is iterable and can be casted to other collection data types such as list, tuple, set, etc.
For example if we want to turn all the elements of an iterable to integers, we can pass the built-in int
function.
The decision whether to use the map function or loops depends on the specific task. Generally speaking, the map function is typically used for simple operations and transformations, while loops are used for more complex operations.
The following example illustrates solving a task with loops and solving the same task using map().
Let us see few more practical examples of using map()
.