Retrieving Mapped Lists in Python 3.x: map() as an Iterator
In Python 3.x, the map() function returns an iterator instead of a list. This change was implemented to improve memory efficiency and optimize performance. However, it poses a challenge if you need to retrieve the mapped values as a list for further processing.
Solution: Converting the Iterator to a List
To retrieve the mapped values as a list, use the list() function to convert the iterator returned by map():
mapped_list = list(map(chr, [66, 53, 0, 94]))
This code will return a list containing the mapped characters: ['B', '5', 'x00', '^'].
Alternative: Using a List Comprehension
A more concise way to convert a list into a list of mapped values is to use a list comprehension:
mapped_list = [chr(c) for c in [66, 53, 0, 94]]
This expression produces the same result as the map() example above.
Iterating Over the Map Object Directly
In certain scenarios, you may not need to convert the map object to a list. You can iterate over the map object directly using a for loop:
for c in map(chr, [65, 66, 67, 68]): print(c)
This code will print the characters "ABCD" without creating an unnecessary list.
The above is the detailed content of How Do I Get a List from Python 3's `map()` Iterator?. For more information, please follow other related articles on the PHP Chinese website!