Enumerate () - generator in Python

I would like to know what happens when I pass the result of the generator function to python enumerate (). Example:

def veryBigHello(): i = 0 while i < 10000000: i += 1 yield "hello" numbered = enumerate(veryBigHello()) for i, word in numbered: print i, word 

Is the listing lazy, or does it all crash into the first? I am 99.999% sure it is lazy, so can I treat it just like a generator function, or do I need to keep track of something?

+41
python iterator generator enumerate
Aug 03 '10 at 12:08
source share
3 answers

This is lazy. It is easy enough to prove that the case:

 >>> def abc(): ... letters = ['a','b','c'] ... for letter in letters: ... print letter ... yield letter ... >>> numbered = enumerate(abc()) >>> for i, word in numbered: ... print i, word ... a 0 a b 1 b c 2 c 
+55
Aug 03 '10 at 12:14
source share

This is even easier said than any of the previous ones:

 $ python Python 2.5.5 (r255:77872, Mar 15 2010, 00:43:13) [GCC 4.3.4 20090804 (release) 1] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> abc = (letter for letter in 'abc') >>> abc <generator object at 0x7ff29d8c> >>> numbered = enumerate(abc) >>> numbered <enumerate object at 0x7ff29e2c> 

If the enumeration does not fulfill the lazy estimate, it will return [(0,'a'), (1,'b'), (2,'c')] or some (almost) equivalent.

Of course, the listing is really just a fantastic generator:

 def myenumerate(iterable): count = 0 for _ in iterable: yield (count, _) count += 1 for i, val in myenumerate((letter for letter in 'abc')): print i, val 
+24
Aug 03 '10 at
source share

Since you can call this function without exception from memory, it is definitely lazy.

 def veryBigHello(): i = 0 while i < 1000000000000000000000000000: yield "hello" numbered = enumerate(veryBigHello()) for i, word in numbered: print i, word 
+9
Aug 03 '10 at 12:15
source share



All Articles