Search code examples
pythonmap-function

Python: Print elements using map function


I'm new to Python and I'm learning how to use map function. I run into following issue:

li=['12','34']
ints=map(int,li)
list(ints) #prints [12,34] OK
p1 = map(print,list(ints))
list(p1)   #prints [] WHY?
p2 = map(print, li)
list(p2)   #prints 12 34 [None, None] OK

I just map print function to list of strings and list of integers and got different result. I cannot see why would p1 and p2 behave differently.


Solution

  • map returns a map object that when exhausted will yield not values. So, when you call list the second time to ints it will not be able to apply the funtion to nothing so then list(map(print,list(ints))) will return an empty list[]

    Check what happens when applying list twice to the same map object:

    >>> li=['12','34']
    >>> ints=map(int,li)
    >>> ints
    <map object at 0x7f4e375c7898>
    >>> list(ints)
    [12, 34]
    >>> list(ints)
    []