Understanding Python’s map() Function: Simple Yet Powerful
Python offers a variety of built-in functions that help streamline data processing tasks, and one of the most useful among them is map()
. Although it may seem unintuitive at first, once understood, it can significantly reduce the amount of code needed—often replacing verbose for
loops with concise and readable expressions.
This article introduces the basics of the map()
function and walks through several practical examples to help you understand its behavior.
Contents
What is map()
?
The map()
function applies a given function to each item in an iterable, such as a list, and returns an iterator with the results.
Basic syntax:
map(function, iterable)
The same function is applied to each element in the iterable.
Example 1: Convert all strings to uppercase
animals = ['dog', 'cat', 'rabbit']
result = map(str.upper, animals)
print(list(result)) # ['DOG', 'CAT', 'RABBIT']
In this case:
str.upper
is a method that converts a string to uppercase.map(str.upper, animals)
appliesstr.upper
to each item in the list.
Example 2: Count the number of characters in each string
animals = ['lion', 'tiger', 'elephant']
result = map(len, animals)
print(list(result)) # [4, 5, 8]
Here, the built-in len
function is applied to each element to return the number of characters.
Example 3: Add a suffix using a lambda function
animals = ['dog', 'cat', 'penguin']
result = map(lambda x: x + 'さん', animals)
print(list(result)) # ['dogさん', 'catさん', 'penguinさん']
This example uses a lambda function to add a suffix (さん
) to each element in the list. This is useful for cases where you need to define simple, one-time-use functions on the fly.
Example 4: Combine two lists element-wise
animals = ['ant', 'spider', 'octopus']
legs = [6, 8, 8]
result = map(lambda a, l: f'{a} has {l} legs', animals, legs)
print(list(result))
# ['ant has 6 legs', 'spider has 8 legs', 'octopus has 8 legs']
In this example, map()
takes two iterables and passes corresponding elements to the lambda function in parallel. This is helpful for generating combined outputs from multiple sources.
Important: The return value of map()
is an iterator
result = map(str.upper, ['dog', 'cat'])
print(result)
# <map object at 0x...>
The result of map()
is a map object (an iterator), which does not immediately display its contents. To see the results, wrap it with list()
:
pythonCopyEditprint(list(result)) # ['DOG', 'CAT']
Summary
Item | Description |
---|---|
Purpose | Apply a function to every element of an iterable |
Common functions | str.upper , len , lambda , etc. |
Return value | Iterator (convert with list() to access the results) |
Use cases | Batch transformations, preprocessing, replacing for-loops |
By mastering map()
, you can write more concise and readable Python code—especially for tasks involving repetitive transformations.
コメントを送信