function while true - list function?

Steven D. Majewski sdm7g at Virginia.EDU
Tue Jul 24 12:28:28 EDT 2001


An alternative to the generator class method:

Also in 2.2, the 'iter' function has two forms: 

  iter( collection )  & 
  iter( callable, sentinel ) 

The second form takes a callable object of no args and a sentinal
value, and returns an iterator that calls the function until it
returns the sentinel value.


For example:

>>> i = iter( [1,2,3,None,4,5,6] )
>>> j = iter( i.next, None )
>>> for x in j: print x
... 
1
2
3
>>> 


So, if you can curry your function into one that takes no args 
( with lambda or by turning it into a class method that keeps 
 state ) or if that's what you've already got, you can just 
use 'iter( function, None )' . 

If you need to force eager evaluation of the iterator you
can use:      [ x for x in iter( function, None ) ] 


-- Steve Majewski






More information about the Python-list mailing list