when an iterable object is exhausted or not

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Aug 4 20:47:02 EDT 2012


On Sat, 04 Aug 2012 12:44:07 -0700, Tim Roberts wrote:

>>$$$ i = filter(lambda c : c.isdigit(), 'a1b2c3') 
>>$$$ for x in i : print(x,end=' ')
>>1 2 3
>>$$$ for x in i : print(x,end=' ')        # i is exhausted
>>$$$
>>
>>IMHO, this should not happen in Py3k.
> 
> It's interesting that it DOESN'T happen in Python 2.  The first "i" is
> of type list, the second "i" is of type string, and both are
> restartable.
>
> What's the type of "i" in the second case in Python 3?


In Python 3, filter returns a lazy iterator, a "filter object". It 
generates items on demand.

In Python 2, filter is eager, not lazy, and generates items all up-front. 
If the input is a string, it generates a string; if the input is a tuple, 
it generates a tuple; otherwise it generates a list.


-- 
Steven



More information about the Python-list mailing list