Home >Backend Development >Python Tutorial >How Do I Convert a Python 3.x Map Object to a List?
Creating a List from a Map in Python 3.x
When mapping a list in Python 3.x, the result is returned as a map object rather than a list. This deviation from Python 2.6 can be addressed by converting the map object into a list using the list() function.
Example:
# Python 2.6 result = map(chr, [66, 53, 0, 94]) # returns a list # Python 3.x result = map(chr, [66, 53, 0, 94]) # returns a map object # Convert the map object to a list result = list(result) # ['B', '5', '\x00', '^']
Alternative Solution:
As an alternative, you can use a list comprehension to directly create a list from the mapped values:
result = [chr(num) for num in [66, 53, 0, 94]] # ['B', '5', '\x00', '^']
Explanation:
In Python 3.x, many functions that operate on iterables return iterators. Iterators consume less memory compared to lists and are suitable for scenarios where you iterate over the elements once. To convert an iterator to a list, you can use the list() function or a list comprehension as described above.
The above is the detailed content of How Do I Convert a Python 3.x Map Object to a List?. For more information, please follow other related articles on the PHP Chinese website!