How to Use Python’s map() Function
In Python, there are three useful global functions - map()
, filter()
, and reduce()
- that we can use to work with collections.
map()
is specifically used to apply a function to each item in an iterable, such as a list, and create a new list with the same number of items, but with modified values.
Let’s take a look at an example that demonstrates the use of map()
. Suppose we have a list of numbers [1, 2, 3]
, and we want to double each number in the list.
1 | numbers = [1, 2, 3] |
In the above code, we define a function double()
that takes a number and returns its double. We then pass this double()
function and the numbers
list to map()
, which applies the function to each item in the list. The result is a new map object.
Alternatively, when the function is a one-liner, it is common to use a lambda function:
1 | numbers = [1, 2, 3] |
In this case, we define a lambda function double
that takes a number and returns its double. Again, we pass the lambda function and the numbers
list to map()
to get the desired result.
Even more concise is to inline the lambda function:
1 | numbers = [1, 2, 3] |
In this example, we directly provide the lambda function as an argument to map()
.
It’s important to note that the original list is left untouched, and map()
returns a map object, which is an iterable. To view the content of the map object, we need to cast it to a list
and print it:
1 | print(list(result)) # [2, 4, 6] |
By using the map()
function, we can easily apply a function to each item in a list and create a new list with the updated values.
tags: [“Python”, “map()”, “functional programming”, “lambda function”]