Map() in python gives output once only
Question:
I was playing with map() function in Python 3.6.3 when I came across this below situation ::
>>> a = [12, 23, 13, 14, 15, 36]
>>> b = [34, 45, 35, 32, 34, 34]
>>> c = [34, 67, 89, 98, 98, 78]
>>> map(lambda x,y,z:x+y+z, a,b,c )
<map object at 0x0000017DD976EC88>
>>> e=map(lambda x,y,z:x+y+z, a,b,c )
>>> list(e)
[80, 135, 137, 144, 147, 148]
>>> list(e)
[]
My question is that why I cannot get output when I used list(e)
second time. It’s showing empty list.
Can anyone help me with this?
Answers:
Because In Python 3, map returns an iterator, which you can only iterate over once. If you iterate over an iterator a second time, it will raise StopIteration immediately, as though it were empty. Thats why you get empty list second time when you call it.
For more info see this question
I hope this helps you! 🙂
I was playing with map() function in Python 3.6.3 when I came across this below situation ::
>>> a = [12, 23, 13, 14, 15, 36]
>>> b = [34, 45, 35, 32, 34, 34]
>>> c = [34, 67, 89, 98, 98, 78]
>>> map(lambda x,y,z:x+y+z, a,b,c )
<map object at 0x0000017DD976EC88>
>>> e=map(lambda x,y,z:x+y+z, a,b,c )
>>> list(e)
[80, 135, 137, 144, 147, 148]
>>> list(e)
[]
My question is that why I cannot get output when I used list(e)
second time. It’s showing empty list.
Can anyone help me with this?
Because In Python 3, map returns an iterator, which you can only iterate over once. If you iterate over an iterator a second time, it will raise StopIteration immediately, as though it were empty. Thats why you get empty list second time when you call it.
For more info see this question
I hope this helps you! 🙂