-1

Just learned that the object returned from map() doesn't hold up once it has been used in a in expression or it was converted into a list.

What is causing b to get emptied at the end?

>>> a = [1, 2, 3]
>>> b = map(lambda x: x, a)
>>> b
<map object at 0x104d8ccc0>
>>> list(b)
[1, 2, 3]
>>> list(b)
[]
msk
  • 105
  • 4
  • My bad. Thanks for the englightenment. Btw, isn't it more natural `map` returning the same collection(type)? Is there any merit in addition to some gain in performance of iteration immediately following it? – msk Jan 20 '19 at 04:16

3 Answers3

3

map outputs an iterator that applies a function (lambda x: x) over some iterators (a). As a result, b is an iterator. When calling list(b) for the first time, the iterator b is called several times until it reaches to its end. Afterward, b is an iterator which does not have any item left to produce. That's why when you call list(b) for the second time, it outputs an empty list.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
noidsirius
  • 409
  • 2
  • 12
  • 1
    OK. it is `iterator` not iterable as I expected. Though not sure about its design idea, it is just as it is. Thanks. – msk Jan 20 '19 at 04:06
1

The documentation for map specifies that it returns an "iterator", not an "iterable". Python defines an iterator to loop exactly once with no repetition; once the end is reached then it will never return another item.

The second execution of list(b) attempts to build a list from an iterator that is already at the end, so it returns no items and an empty list is constructed.

lehiester
  • 836
  • 2
  • 7
  • 17
-2

Whenever you are calling list(b) you are using the iterator in it and then clearing the variable b if you want to store b as a list use a = [1, 2, 3] b = list(map(lambda x: x, a)) print(b)

[1, 2, 3] print(*b) 1 2 3 Hope this helped.

EDIT: Fixed My Mistake.