- Published on
Understanding the `map` Function in Python
- Authors
- Name
- hwahyeon
I recently attended an open online course on writing Python code in a more Pythonic way. Today's lesson was about lists.
When a two-dimensional list mylist
containing integers is given as a parameter to the solution
function, you can write the function to return a list containing the lengths of each element in mylist
as follows:
def solution(mylist):
res = []
for i in mylist:
res.append(len(i))
return res
solution([[1, 2], [3, 4], [5]])
# Output: [2, 2, 1]
However, this can be written more concisely using the map
function:
Using the map
function allows you to apply a function to each element of a list without using a loop, making the code more concise and, in some cases, improving performance.
def solution(mylist):
return list(map(len, mylist))
solution([[1, 2], [3, 4], [5]])
# Output: [2, 2, 1]
The map
function applies the specified function to each element of one or more iterables and returns the results as a new iterable. Note that map
returns a map
object, so you need to convert it to a list or another type to view the result.
map
function
Structure of the map(function, iterable, ...)
function
: The function to apply to each element. It usually takes one argument, but it can take multiple arguments when multiple iterables are used.iterable
: The iterable(s) thatmap
will iterate over while applying the function.
Example 1: Applying a function to each element of a list
def square(x):
return x * x
numbers = [1, 2, 3, 4, 5]
squared = map(square, numbers)
print(list(squared))
This code applies the square
function to every element in the numbers
list and prints the result.
Example 2: When the function takes multiple arguments
def add(x, y):
return x + y
numbers1 = [1, 2, 3]
numbers2 = [4, 5, 6]
added = map(add, numbers1, numbers2)
print(list(added))
# Output: [5, 7, 9]
In this example, the add
function takes two arguments from numbers1
and numbers2
and returns their sum. For instance, the first elements of numbers1
and numbers2
are paired together and passed to the add
function.
Using the map
function allows you to apply a function to elements from multiple iterables in a concise manner, making the code more readable and easier to maintain.