Home >Backend Development >Python Tutorial >How to Convert Python 3's `map` Object to a List?

How to Convert Python 3's `map` Object to a List?

DDD
DDDOriginal
2024-12-15 02:14:14969browse

How to Convert Python 3's `map` Object to a List?

Converting Map Objects to Lists in Python 3.x

In Python 3.x, the map() function returns an iterator by default instead of a list. This can be inconvenient if you want to use the mapped elements directly.

Problem Statement

A common task is to convert a list of integers into their hexadecimal representations. In Python 2.6, this was straightforward using the map() function, as shown below:

# Python 2.6
hex_list = map(chr, [66, 53, 0, 94])  # Return a list of hex characters

However, in Python 3.1, the above code returns a map object:

# Python 3.1
hex_map = map(chr, [66, 53, 0, 94])  # Return a map object

Solution

To retrieve the actual list of mapped elements in Python 3.x, you can use the list() function to convert the map object into a list:

hex_list = list(map(chr, [66, 53, 0, 94]))

Better Alternative

An alternative approach to mapping a list of integers to their hexadecimal representations is to use a list comprehension, as follows:

hex_list = [chr(n) for n in [66, 53, 0, 94]]

This approach eliminates the need to use the map() function and creates a list directly.

Iterating over Map Objects

Note that you can still iterate over a map object in Python 3.x without converting it to a list first:

for ch in map(chr, [65, 66, 67, 68]):
    print(ch)  # Prints "ABCD"

The above is the detailed content of How to Convert Python 3's `map` Object to a List?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn