0

In the below code, why do I get different outputs? After iterating over the first arr, I can't make a list out of it (it's empty). However, if I do the same before iterating, as seen in the second part of the code, the set gets created, but when iterating after that, it seems like arr2 is empty. Why does this happen and how to avoid/fix it?

arr = map(int, [1,2,3])

for item in arr:
    print(item)    

myset = set(arr)
print(myset)

# Output:
# 1
# 2
# 3
set()    

########################

arr2 = map(int, [1,2,3])

newset = set(arr2)
print(newset)

for item in arr2:
    print(item)

# Output:
# {1, 2, 3}
  • You can make `arr2` a list to preserve its contents `arr2 = list(map(int, [1,2,3]))` – snakecharmerb May 01 '20 at 16:16
  • Yeah, I know, thanks. However, why does this happen if I don't transform it into a list? –  May 01 '20 at 16:28
  • What did you expect? What should the iterator do after being consumed? – mata May 01 '20 at 16:30
  • Iterators are one-use by design; there's no way to "go back to the beginning", hence you need to store the output of an iterator in a container - like a list - if you want to be able to iterate over the same values again, and you weren't iterating over a container in the first place. – snakecharmerb May 01 '20 at 16:47
  • Thanks, I wrote the comment before reading the answers of the already asked question. –  May 01 '20 at 20:37

0 Answers0