2

I tried the below code:

squared = (map(lambda x: x**2, items))
print(list(squared))
print(list(squared))

First, it prints the list of squared numbers, again printing the same thing prints an empty list. I want to know what is the reason behind this.

Georgy
  • 12,464
  • 7
  • 65
  • 73
Jp Mohan
  • 160
  • 2
  • 7
  • 4
    In Python 3.x, `map()` produces an iterator rather than a list. After iterating over that iterator once (such as what `list()` does to make an actual list out of it), it's empty - further iteration will not produce any values. Assign `list(map(...))` to a variable if you're going to need it more than once. – jasonharper Mar 27 '19 at 13:12

3 Answers3

1

map returns an iterator which can only be iterated over once as per: https://docs.python.org/3/library/stdtypes.html#typeiter.

ame
  • 446
  • 3
  • 5
0

As mentionned by others, the iterator that you create can only be used once so saving the result and reusing that is the way to go.

items = [0,1,2,3,4,5,6,7,8,9]

squared = (map(lambda x: x**2, items))
abc = list(squared)
print(abc)
print(abc)
print(abc)
print(abc)

As a side note, you should have a definition for items in your question like I have put in. That would allow us to copy-paste your whole code and quickly see what's going on instead of getting an error.

Hoog
  • 2,280
  • 1
  • 14
  • 20
0

In Python 3, map returns an iterator, which you can only iterate over once. If you iterate over an iterator a second time, it will raise Stop Iteration immediately, as though it were empty. max consumes the whole thing, and min sees the iterator as empty. If you need to use the elements more than once, you need to call list to get a list instead of an iterator.