Issue 4337: Iteration over a map object with list() (original) (raw)

win XP sp2, Py3.0c2

I had to face an annoying problem when iterating over a map object.

With a range class, this works

r = range(5) list(r) [0, 1, 2, 3, 4]

With dict_keys/values/items objects, the following works

d = {1: 'a', 2:'b', 3:'c'} list(d.keys()) [1, 2, 3] list(d.values()) ['a', 'b', 'c'] list(d.items()) [(1, 'a'), (2, 'b'), (3, 'c')]

But with a map object...

def plus(i): return i + 1

a = list(range(3)) a [0, 1, 2] r = map(plus, a) r <map object at 0x01371570> for e in r: print(e)

1 2 3

list(r) [] #empty list!

Bug or feature?

2008/11/17 Raymond Hettinger <report@bugs.python.org>

Raymond Hettinger <rhettinger@users.sourceforge.net> added the comment:

Feature :-)

You will get the expected result if you skip the step where you ran the for-loop over r before running list(). Either listing or for-looping will exhaust the iterator. This is how iterators work.


nosy: +rhettinger resolution: -> invalid status: open -> closed


Python tracker <report@bugs.python.org> <http://bugs.python.org/issue4337>


Thanks for the reply and sorry for the noise. Indeed, you are right and for some "strange personal reasons" (bad habits?), I frequently fall in this trap.

return i + 1

[1, 2, 3, 4]

Regards