Skip to content Skip to sidebar Skip to footer

Python - Printing Map Object Issue

I was playing with the map object and noticed that it didn't print if I do list() beforehand. When I viewed only the map beforehand, the printing worked. Why?

Solution 1:

map returns an iterator and you can consume an iterator only once.

Example:

>>>a=map(int,[1,2,3])>>>a
<map object at 0x1022ceeb8>
>>>list(a)
[1, 2, 3]

>>>next(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

>>>list(a)
[]

Another example where I consume the first element and create a list with the rest

>>>a=map(int,[1,2,3])>>>next(a)
1 
>>>list(a)
[2, 3]

Solution 2:

As per the answer from @newbie, this is happening because you are consuming the map iterator before you use it. (Here is another great answer on this topic from @LukaszRogalski)

Example 1:

w = [[1,5,7],[2,2,2,9],[1,2],[0]]
m = map(sum,w) # map iterator is generatedlist(m) # map iterator is consumed here (output: [13,15,3,0])for v in m:
    print(v) # there is nothing left in m, so there's nothing to print

Example 2:

w = [[1,5,7],[2,2,2,9],[1,2],[0]]
m = map(sum,w) #map iterator is generatedfor v in m:
    print(v) #map iterator is consumed here# if you try and print again, you won't get a resultfor v in m:
    print(v) # there is nothing left in m, so there's nothing to print

So you have two options here, if you only want to iterate the list once, Example 2 will work fine. However, if you want to be able to continue using m as a list in your code, you need to amend Example 1 like so:

Example 1 (amended):

w = [[1,5,7],[2,2,2,9],[1,2],[0]]
m = map(sum,w) # map iterator is generated
m = list(m) # map iterator is consumed here, but it is converted to a reusable list.

for v in m:
    print(v) # now you are iterating a list, so you should have no issue iterating# and reiterating to your heart's content!

Solution 3:

It's because it return an generator so clearer example:

>>>gen=(i for i in (1,2,3))>>>list(gen)
[1, 2, 3]
>>>for i in gen:
    print(i)


>>>

Explanation:

  • it's because to convert it into the list it basically loops trough than after you want to loop again it will think that still continuing but there are no more elements

so best thing to do is:

>>>M=list(map(sum,W))>>>M
[13, 15, 3, 0]
>>>for i in M:
        print(i)
13
15
3
0

Solution 4:

You can either use this:

list(map(sum,W))

or this:

{*map(sum,W)}

Post a Comment for "Python - Printing Map Object Issue"