1

Why do I get in Python2

>>> map(max,[1,2],[3,1])
[3, 2]

and in Python3

>>> map(max,[1,2],[3,1])
<map object at 0x10c2235f8>

?

What should replace map(max,[1,2],[3,1]) in Python3 ?

I read that one should use list comprehension in Python3 but

>>> [max(i,j) for i in [1,2] for j in [3,1]]
[3, 1, 3, 2]

does not give the desired result and neither do the variations that came to mind.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • 1
    @Dark technically, not a generator, just an iterator. – juanpa.arrivillaga Dec 21 '17 at 03:59
  • list-comp: `[max(i, j) for i, j in zip([1,2], [3,1])]`. – ekhumoro Dec 21 '17 at 04:04
  • @ekhumoro: thanks this is elegant. Do python programmers have an opinion on which of the two solutions (using list or using zip and comprehension) is more appropriate? – Alexander Kurz Dec 21 '17 at 09:25
  • @AlexanderKurz. There are probably SO questions that discuss the relative performance. Otherwise, it's really just a matter of personal taste, or house style (or even just "what looks right" in the current code context). – ekhumoro Dec 21 '17 at 19:08

1 Answers1

2

That's because Python2 returns a List for multiple return values.

From Pydoc[2]:

If there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation). The iterable arguments may be a sequence or any iterable object; the result is always a list.

Whereas Python3 returns an Iterable.

From Pydoc[3]:

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


So to get the list in Python3, just do :

list(map(...))

Basically :

>>> list(map(max,[1,2],[3,1]))
=> [3, 2]
Kaushik NP
  • 6,733
  • 9
  • 31
  • 60
  • thanks ... do python programmers have an opinion on which of the two solutions (using list or using zip and comprehension) is preferable? – Alexander Kurz Dec 21 '17 at 09:27
  • The above solution is the preffered way since you can use the iterable itself using `.next` instead of going for lists and also has shorter code and is easier to read. – Kaushik NP Dec 21 '17 at 17:09