HasNext in Python Iterators?

Did Python iterators get a hasNext method?

+85
python iterator
Dec 27 '09 at 18:04
source share
12 answers

No, there is no such method. The exception is the end of the iteration. See the documentation.

+61
Dec 27 '09 at 18:08
source share

As an alternative to StopIteration , next(iterator, default_value) .

For exapmle:

 >>> a = iter('hi') >>> print next(a, None) h >>> print next(a, None) i >>> print next(a, None) None 

That way, you can detect for None or another setpoint for the end of the iterator if you don't want the exception path.

+117
Mar 25 '13 at 3:05
source share

If you really need a has-next (because you just correctly transcribe the algorithm from the reference implementation in Java, say, or because you write a prototype that will need to be easily ported to Java when it finishes), it's easy to get it with a small class -shell. For example:

 class hn_wrapper(object): def __init__(self, it): self.it = iter(it) self._hasnext = None def __iter__(self): return self def next(self): if self._hasnext: result = self._thenext else: result = next(self.it) self._hasnext = None return result def hasnext(self): if self._hasnext is None: try: self._thenext = next(self.it) except StopIteration: self._hasnext = False else: self._hasnext = True return self._hasnext 

now something like

 x = hn_wrapper('ciao') while x.hasnext(): print next(x) 

emits

 c i a o 

as needed.

Note that using next(sel.it) as the built-in requires Python 2.6 or better; if you are using an older version of Python, use self.it.next() instead (and similarly for next(x) in the use case). [[You may reasonably think that this note is redundant since Python 2.6 has been around for more than a year - but more often than not, when I use the Python 2.6 functions in the answer, some commentator or other user feels the obligation to indicate that they have 2.6 functions, so I'm trying to prevent such comments at a time; -)]]

+28
Dec 27 '09 at 21:02
source share

Try the __length_hint __ () method from any iterator object:

 iter(...).__length_hint__() > 0 
+8
Dec 31 '09 at 0:06
source share

In addition to all the StopIteration mentions, the Python "for" loop just does what you want:

 >>> it = iter("hello") >>> for i in it: ... print i ... h e l l o 
+7
Dec 28 '09 at 2:52
source share

hasNext somewhat converted to a StopIteration exception, for example:

 >>> it = iter("hello") >>> it.next() 'h' >>> it.next() 'e' >>> it.next() 'l' >>> it.next() 'l' >>> it.next() 'o' >>> it.next() Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration 
+5
Dec 27 '09 at 18:11
source share

No. The most similar concept is most likely the exception StopIteration.

+3
Dec 27 '09 at 18:07
source share

You can tee use the iterator, itertools.tee , and check for StopIteration on the StopIteration iterator.

+3
Dec 28 '09 at 3:25
source share

I believe that python just has next (), and according to the document, it throws an exception, there are no more elements.

http://docs.python.org/library/stdtypes.html#iterator-types

+2
Dec 27 '09 at 18:07
source share

A usage example that will lead me to the search is as follows:

 def setfrom(self,f): """Set from iterable f""" fi = iter(f) for i in range(self.n): try: x = next(fi) except StopIteration: fi = iter(f) x = next(fi) self.a[i] = x 

where hasnext () is available, you can do

 def setfrom(self,f): """Set from iterable f""" fi = iter(f) for i in range(self.n): if not hasnext(fi): fi = iter(f) # restart self.a[i] = next(fi) 

which is cleaner for me. Obviously, you can solve problems by setting utility classes, but then it happens that you have twenty-four different almost equivalent workarounds, each of which is related to their quirks, and if you want to reuse code that uses different workarounds, you you need to either have several close to the equivalent in one application, or bypass the selection and rewriting of code to use the same approach. “Do it once and do it well,” the maximum fails.

In addition, the iterator itself must have an internal hasnext check to see if it needs to throw an exception. This internal check is then hidden so that it needs to be tested, trying to get the element, catching the exception and running the handler if it was thrown. This does not need to hide IMO.

+1
Jan 12 '14 at 16:49
source share

A good approach for such questions / problems is to check what we have in the directory (object / method / iterator / type / class / ...)

you will see that dir(iterator) return __length_hint__

and iterator.__length_hint__() positive until the end of the iteration.

what he.

0
Feb 19 '14 at 9:21
source share

I like it:

 While(True): try: # Do something with the next value iterator.next() except StopIteration: break 
0
Aug 07 '15 at 21:34
source share



All Articles