Has Next in Python Iterators
Ben Finney
ben+python at benfinney.id.au
Thu Oct 21 07:37:18 EDT 2010
Kelson Zawack <zawackkfb at gis.a-star.edu.sg> writes:
> […] if I want to iterate until an element that might or might not be
> present is found I either wrap the while loop in a try block or break
> out of a for loop.
I'm not sure what exception you would catch, but that could be a good
solution.
The general solution would be to break from the ‘for’ loop when you find
the terminating item.
> Since an iterator having an end is not actually an exceptional case
Right. You're not talking about the end of the iterator, though; you're
talking about stopping *before* the end, when a particular item is
reached.
Either that, or you'll need to be clearer about what the problem is.
A simple, complete, working example would help.
> and the for construct is really for iterating though the entirety of a
> list
Or until something else happens to change the flow, such as a ‘break’
statement.
> both of these solutions feel like greasy workarounds and thus not
> very pythonic.
Show us a simple, complete, working example, and let's see how Pythonic
it looks.
> Is there something I am missing? Is there a reason python iterators
> don't have has_next functionality?
Many iterators can't know whether they have a next item without actually
generating that item.
> What is the standard solution to this problem?
I'm not sure that it is a problem. Let's see the example, to make it
more concrete.
--
\ “We must respect the other fellow's religion, but only in the |
`\ sense and to the extent that we respect his theory that his |
_o__) wife is beautiful and his children smart.” —Henry L. Mencken |
Ben Finney
More information about the Python-list
mailing list