When I convert a map object to list object in Python using list(), and apply list() again to this list, why does the list become empty?

Question:

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?

Asked By: Jyotsna Masand

||

Answers:

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.

Answered By: Prune
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.