![]() |
VOOZH | about |
map() function in Python applies a given function to each element of an iterable (list, tuple, set, etc.) and returns a map object (iterator). It is a higher-order function used for uniform element-wise transformations, enabling concise and efficient code.
Let's start with a simple example of using map() to convert a list of strings into a list of integers.
[1, 2, 3, 4]
Explanation: map() applies int() to each element in 's' which changes their datatype from string to int.
map(function, iterable,..)
Parameters:
Note: You can pass multiple iterables if the function accepts multiple arguments.
By default, map() function returns a map object, which is an iterator. In many cases, we will need to convert this iterator to a list to work with the results directly.
Example: Let's see how to double each element of the given list.
[2, 4, 6, 8]
Explanation:
We can use a lambda function instead of a custom function with map() to make code shorter and easier. Let's see how to improve above code for better readability.
[1, 4, 9, 16]
Explanation:lambda x: x ** 2 squares each number and the results are converted into a list.
We can use map() with multiple iterables if the function we are applying takes more than one argument.
Example: In this example, map() takes two iterables (a and b) and applies lambda function to add corresponding elements from both lists.
[5, 7, 9]
Explanation: map() takes x from 'a' and 'y' from b and adds them.
This example shows how we can use map() to convert a list of strings to uppercase.
['APPLE', 'BANANA', 'CHERRY']
Explanation:str.upper method is applied to each element in the list fruits using map(). The result is a list of uppercase versions of each fruit name.
In this example, we use map() to extract the first character from each string in a list.
['a', 'b', 'c']
Explanation: lambda s: s[0] extracts first character from each string in the list words. map() applies this lambda function to every element, resulting in a list of the first characters of each word.
In this example, We can use map() to remove leading and trailing whitespaces from each string in a list.
['hello', 'world', 'python']
Explanation:str.strip method removes leading and trailing whitespaces from each string in list strings. map() function applies str.strip to each element and returning a list of trimmed strings.
In this example, we use map() to convert a list of temperatures from Celsius to Fahrenheit.
[32.0, 68.0, 98.6, 212.0]
Explanation: