New (?) suggestion re: 'while x = f(): ...'

Delaney, Timothy tdelaney at avaya.com
Wed May 29 18:52:48 EDT 2002


> From: Jeff Epler [mailto:jepler at unpythonic.net]
> 
> Not quite -- H will stop on "any false value", while iter(f, "") will
> stop on a single value.
> 
> Now, if iter would take a function as a second argument...
> 
>     def myiter(f, g):
> 	if callable(g):
> 	    while 1:
> 		v = f()
> 		if g(v): break
> 		yield v
> 	else:
> 	    while 1:
> 		v = f()
> 		if v==g: break
> 		yield v
> then myiter(f, lambda x: not x) would be the equivalen of H(f).

iter(o[, sentinel]) 

Return an iterator object. The first argument is interpreted very
differently depending on the presence of the second argument. Without a
second argument, o must be a collection object which supports the iteration
protocol (the __iter__() method), or it must support the sequence protocol
(the __getitem__() method with integer arguments starting at 0). If it does
not support either of those protocols, TypeError is raised. If the second
argument, sentinel, is given, then o must be a callable object. The iterator
created in this case will call o with no arguments for each call to its
next() method; if the value returned is equal to sentinel, StopIteration
will be raised, otherwise the value will be returned. New in version 2.2.

Tim Delaney





More information about the Python-list mailing list