Logo

How to get a map() to return a list in Python 3.x?

In Python 3.x, the built-in map() function returns an iterator instead of a list. This design choice conserves memory by not creating an entire list in one go. However, if you need a list, simply wrap your map() call with the list() constructor:

def square(x): return x * x nums = [1, 2, 3, 4] squared_list = list(map(square, nums)) print(squared_list) # Output: [1, 4, 9, 16]

1. Iterator by Default:

  • In Python 2, map() returned a list. In Python 3, it returns a “map object,” which is an iterator.

2. Convert to List:

  • Use list(map(...)) when you need a list for further operations like indexing or slicing.

3. Why This Matters:

  • Performance: Iterators can be more memory-efficient than lists, especially with large data sets.
  • Flexibility: Converting to a list is simple and explicit, so you only do it when truly necessary.

Level Up Your Python Skills

If you’re eager to sharpen your Python skills, especially for technical interviews or larger-scale projects, check out these courses from DesignGurus.io:

And if you’re exploring system design alongside your Python journey, you might find Grokking System Design Fundamentals helpful for mastering distributed systems and large-scale architecture essentials.

Key Takeaway: In Python 3, map() yields an iterator for memory efficiency. Wrap your map() call with list() when a list structure is required.

TAGS
Python
CONTRIBUTOR
TechGrind