0

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?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Prates
  • 39
  • 4
  • As ForceBru says in the answer below, `newList` is a map generator, not a list. If you want `newList` to actually be a list, you could use `newList = list(map(myfunc, myList))` which would make things work as you expect. – Joachim Isaksson Nov 11 '19 at 20:25

1 Answers1

4

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.

ForceBru
  • 43,482
  • 10
  • 63
  • 98