Unexpected behavior in Python 3: The list contents disappear after printed
Question:
I’m learning Python and while doing some coding to practice I duplicated one line and the result was unexpected.
def myfunc(x):
return x*2
myList = [1,2,3,4,5]
newList = map(myfunc, myList)
print('Using myfunc on the original list: ',myList,' results in: ',list(newList))
print('Using myfunc on the original list: ',myList,' results in: ',list(newList))
I would expect to see the same result twice, but I’ve got this:
Using myfunc on the original list: [1, 2, 3, 4, 5] results in: [2, 4, 6, 8, 10]
Using myfunc on the original list: [1, 2, 3, 4, 5] results in: []
Why does this happen and how to avoid it?
Answers:
newList
is not a list. It’s a generator that yields data on demand and will be exhausted after you retrieve all the data it holds with list(newList)
. So, when you call list(newList)
again, there’s no more data to put in the list, so it remains empty.
I’m learning Python and while doing some coding to practice I duplicated one line and the result was unexpected.
def myfunc(x):
return x*2
myList = [1,2,3,4,5]
newList = map(myfunc, myList)
print('Using myfunc on the original list: ',myList,' results in: ',list(newList))
print('Using myfunc on the original list: ',myList,' results in: ',list(newList))
I would expect to see the same result twice, but I’ve got this:
Using myfunc on the original list: [1, 2, 3, 4, 5] results in: [2, 4, 6, 8, 10]
Using myfunc on the original list: [1, 2, 3, 4, 5] results in: []
Why does this happen and how to avoid it?
newList
is not a list. It’s a generator that yields data on demand and will be exhausted after you retrieve all the data it holds with list(newList)
. So, when you call list(newList)
again, there’s no more data to put in the list, so it remains empty.