0

Please follow along this code:

def addition(n): 
    return n + n

numbers = (1, 2, 3, 4) 
result = map(addition, numbers) 
print(list(result))

Output: [2, 4, 6, 8]

Now when I apply list() again on result, which has already become a list, result turns out to be empty.

list(result)

Output: []

Why is this so?

1 Answers1

3

The map object is a generator.

list(result)

involves iterating through the iterator. The iterator is now finished. When you try again, there is no data to return, so you have an empty list. If you reset the iterator in some way, you can get the expected results.

This is something like reading an entire file, and then wondering why your next read loop doesn't return anything: you're at the end.

Prune
  • 76,765
  • 14
  • 60
  • 81