0

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?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Dibakar Bose
  • 100
  • 1
  • 8
  • Does this answer your question? [How can I iterate twice over the same data with a given iterator?](https://stackoverflow.com/questions/25336726/how-can-i-iterate-twice-over-the-same-data-with-a-given-iterator) – Karl Knechtel Jan 07 '23 at 07:14

1 Answers1

1

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! :)

Community
  • 1
  • 1
Abdullah Ahmed Ghaznavi
  • 1,978
  • 3
  • 17
  • 27