Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is enumerate in python lazy?

I'd like to know what happens when I pass the result of a generator function to python's 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 enumeration iterated lazily, or does it slurp everything into the <enumerate object> first? I'm 99.999% sure it's lazy, so can I treat it exactly the same as the generator function, or do I need to watch out for anything?

like image 432
Adam Avatar asked Aug 03 '10 12:08

Adam


People also ask

What does enumerate () do in Python?

What does enumerate do in Python? The enumerate function in Python converts a data collection object into an enumerate object. Enumerate returns an object that contains a counter as a key for each value within an object, making items within the collection easier to access.

Is enumerate an iterator?

In this example, you assign the return value of enumerate() to enum . enumerate() is an iterator, so attempting to access its values by index raises a TypeError . Fortunately, Python's enumerate() lets you avoid all these problems.

Is enumerate a method in Python?

Enumerate() in PythonEnumerate() method adds a counter to an iterable and returns it in a form of enumerating object. This enumerated object can then be used directly for loops or converted into a list of tuples using the list() method.

What is the point of enumerate?

enumerate() allows us to iterate through a sequence but it keeps track of both the index and the element. The enumerate() function takes in an iterable as an argument, such as a list, string, tuple, or dictionary.


1 Answers

It's lazy. It's fairly easy to prove that's 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 
like image 124
Dave Webb Avatar answered Nov 15 '22 16:11

Dave Webb