Python: using map function

I'm having problems with the map function. When I want to print the created list, the interpreter shows a pointer:

 >>> squares = map(lambda x: x**2, range(10)) >>> print(squares) <map object at 0x0000000002A086A0> 

What is the problem?

+4
source share
4 answers

The problem is that the list is not created. map returns a specific type of generator in Python 3, which is not a list (but rather a "map object", as you can see), you can try

 print(list(squares)) 

Or just use list comprehension to get the list first (which seems to work better anyway):

 squares = [x**2 for x in range(10)] 

map used to return the list in Python 2.x, and the change made in Python 3 is described in the this section of the documentation:

  • map() and filter() return iterators. If you really need a list, a quick fix, for example. list(map(...)) , but it’s better to fix it often using list comprehension (especially when the source code uses lambda ) , or rewrite the code so that it doesn’t need a list at all. It is especially difficult to use map() for side effects of a function; the correct conversion is to use a regular for loop (since creating a list would be just wasteful).
+5
source

map returns generator , i.e. this is what can be used for looping as needed. To get the actual list, do print(list(squares)) . Or

 for a in squares: print a 

Update: at first it looks weird, but imagine that you have 1 millionaire. If he immediately creates a list, you will need to allocate memory for 1mio elements, even if you may ever want to watch only one at a time. If there is a generator, a complete list of elements will be stored only in memory, if necessary.

+1
source

map () changed between python 2 and 3. In python 2, the map would apply the function to iterable and return a list. In python 3, map returns a generator that applies this function to the iterator when you loop it.

python2:

 >>> print map(lambda x: x**2, range(10)) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 

python3:

 >>> print(map(lambda x: x**2, range(10))) <map object at 0x7fb4b7c82250> >>> print([x for x in map(lambda x: x**2, range(10))]) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 
+1
source

You can use unpacking as follows:

 >>> [*map(lambda x: x**2, range(10))] [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 
0
source

Source: https://habr.com/ru/post/1495585/


All Articles