Resolving Map Function Issue In Python 3 Vs Python 2
Solution 1:
As documented, in the migration guide,
In Python 2 map() returns a list while in Python 3 it returns an iterator.
Apply function to every item of iterable and return a list of the results.
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.
Solution 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:
- Apply the first transformation to the entire list, then the second, etc.
- 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.
Post a Comment for "Resolving Map Function Issue In Python 3 Vs Python 2"