Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does map return a map object instead of a list in Python 3?

I am interested in understanding the new language design of Python 3.x.

I do enjoy, in Python 2.7, the function map:

Python 2.7.12 In[2]: map(lambda x: x+1, [1,2,3]) Out[2]: [2, 3, 4] 

However, in Python 3.x things have changed:

Python 3.5.1 In[2]: map(lambda x: x+1, [1,2,3]) Out[2]: <map at 0x4218390> 

I understand the how, but I could not find a reference to the why. Why did the language designers make this choice, which, in my opinion, introduces a great deal of pain. Was this to arm-wrestle developers in sticking to list comprehensions?

IMO, list can be naturally thought as Functors; and I have been somehow been thought to think in this way:

fmap :: (a -> b) -> f a -> f b 
like image 545
NoIdeaHowToFixThis Avatar asked Oct 13 '16 08:10

NoIdeaHowToFixThis


People also ask

Why does map Return map Python?

Python map() function map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.) Parameters : fun : It is a function to which map passes each element of given iterable.

How do I turn a map into a list in Python?

Use the list() class to convert a map object to a list, e.g. new_list = list(map(my_fuc, my_list)) . The list class takes an iterable (such as a map object) as an argument and returns a list object. Copied!

What type does map return Python?

The map() function applies a given function to each item of an iterable (list, tuple etc.) and returns an iterator.

What does map () do in Python?

Python's map() is a built-in function that allows you to process and transform all the items in an iterable without using an explicit for loop, a technique commonly known as mapping. map() is useful when you need to apply a transformation function to each item in an iterable and transform them into a new iterable.


1 Answers

I think the reason why map still exists at all when generator expressions also exist, is that it can take multiple iterator arguments that are all looped over and passed into the function:

>>> list(map(min, [1,2,3,4], [0,10,0,10])) [0,2,0,4] 

That's slightly easier than using zip:

>>> list(min(x, y) for x, y in zip([1,2,3,4], [0,10,0,10])) 

Otherwise, it simply doesn't add anything over generator expressions.

like image 60
RemcoGerlich Avatar answered Sep 17 '22 22:09

RemcoGerlich