Home > Backend Development > Python Tutorial > How Do I Get a List from Python 3's `map()` Iterator?

How Do I Get a List from Python 3's `map()` Iterator?

Linda Hamilton
Release: 2024-12-09 22:17:10
Original
637 people have browsed it

How Do I Get a List from Python 3's `map()` Iterator?

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]))
Copy after login

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]]
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template