Home > Backend Development > Python Tutorial > How Do I Convert a Map Iterator to a List in Python 3.x?

How Do I Convert a Map Iterator to a List in Python 3.x?

Mary-Kate Olsen
Release: 2024-12-19 21:20:10
Original
723 people have browsed it

How Do I Convert a Map Iterator to a List in Python 3.x?

Retrieving a List from a Map in Python 3.x

In Python 2.6, mapping an iterable to a new value using the map function returned a list. However, in Python 3.x, the map function returns an iterator, which can be more memory-efficient.

To retrieve the mapped values as a list in Python 3.x, you can use the list constructor:

my_list = list(map(chr, [66, 53, 0, 94]))
Copy after login

Alternative Approaches

Alternatively, there are other ways to convert an iterable to a list of hex values:

  • Using a list comprehension:
my_list = [hex(i) for i in [66, 53, 0, 94]]
Copy after login
  • Using the join function with a generator expression:
my_list = list("\x" + hex(i)[2:] for i in [66, 53, 0, 94])
Copy after login

Performance Considerations

In general, using a list comprehension is more efficient than using a loop with a map object. However, if you need to iterate over the values multiple times, using a map object can save memory since it lazily produces values.

The above is the detailed content of How Do I Convert a Map Iterator to a List in Python 3.x?. 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