5

I'm interested in functional programming with python and am working through Mary Rose Cook's blog post A practical introduction to functional programming.

Apparently, it was written in python 2 as this:

name_lengths = map(len, ["Mary", "Isla", "Sam"])

print name_lengths
# => [4, 4, 3]

in Python 3 yields this:

<map object at 0x100b87a20>

I have two questions:

  1. Why is this is so?
  2. Other than converting the map object to a list and then use numpy, are there any other solutions?
PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
hrokr
  • 3,276
  • 3
  • 21
  • 39
  • Numpy is irrelevant to the problem. The answer for the other question mentions converting to a Numpy array because OP wanted a Numpy array as a result. The 2.x result is a list; if you want the same result, then converting to a list is obviously sufficient. – Karl Knechtel Jan 07 '23 at 07:17

2 Answers2

9

As documented, in the migration guide,

In Python 2 map() returns a list while in Python 3 it returns an iterator.

Python 2:

Apply function to every item of iterable and return a list of the results.

Python 3:

Return an iterator that applies function to every item of iterable, yielding the results.

Python 2 always does the equivalent of list(imap(...)), Python 3 allows for lazy evaluation.

dhke
  • 15,008
  • 2
  • 39
  • 56
2

To supplement @dhke's excellent answer (this is too long for a comment) think of it this way. You want to perform multiple transformations on a list by combining map, filter, etc. So there are two ways to think of this:

  1. Apply the first transformation to the entire list, then the second, etc.
  2. Apply all the transformations to the first element of the list, then the second, etc.

The python3 way allows for either, whereas the second cannot be written as succinctly in python 2: you would have to explicitly iterate the list with a for loop and build up a new list of the results.

Jared Smith
  • 19,721
  • 5
  • 45
  • 83