1
def addition(n):
    return n + n 
numbers = (1, 2, 3, 4)
result = map(addition, numbers)
print(list(result))
print(set(result))
print(tuple(result))

Output - [2, 4, 6, 8] set() ()

Why is only the print of list is executing correctly, the succeeding set and tuple are printing empty objects?

  • 3
    Because you've consumed the iterator into the list. The others get an empty iterator. – jonrsharpe Oct 03 '21 at 15:40
  • Does this answer your question? [Python: casting map object to list makes map object empty?](https://stackoverflow.com/questions/45017937/python-casting-map-object-to-list-makes-map-object-empty) – jonrsharpe Oct 03 '21 at 15:41
  • The above posts have answer your question clearly. TO confirm the new understanding - you can add/modify this line: `result = list(map(addition, numbers))` to see what's the difference – Daniel Hao Oct 03 '21 at 15:43

1 Answers1

2

I think that once you use the map object once, you cannot reuse it. I ran my own tests on IDLE, and I found that if you change the code so that print(set(result)) comes first, this is the output:

{8, 2, 4, 6}
[]
()
Dharman
  • 30,962
  • 25
  • 85
  • 135
Cerdipinki
  • 82
  • 6