Is there an alternative way to call next on python generators?

I have a generator, and I would like to know if I can use it without worrying about StopIteration, and I would like to use it without for item in generator . I would like to use it with a while statement (or other constructs). How can i do this?

+3
python language-features
Feb 01 '09 at 10:48
source share
4 answers

Use this to wrap your generator:

 class GeneratorWrap(object): def __init__(self, generator): self.generator = generator def __iter__(self): return self def next(self): for o in self.generator: return o raise StopIteration # If you don't care about the iterator protocol, remove this line and the __iter__ method. 

Use it as follows:

 def example_generator(): for i in [1,2,3,4,5]: yield i gen = GeneratorWrap(example_generator()) print gen.next() # prints 1 print gen.next() # prints 2 

Update: Please use the answer below because it is much better than this.

-one
Feb 01 '09 at 11:13
source share

built-in function

next (iterator [, default])
Extract the next element from the iterator by calling its __next__() method. If the default value is set, it is returned if the iterator is exhausted, otherwise StopIteration will be raised.

In Python 2.5 and later:

 raiseStopIteration = object() def next(iterator, default=raiseStopIteration): if not hasattr(iterator, 'next'): raise TypeError("not an iterator") try: return iterator.next() except StopIteration: if default is raiseStopIteration: raise else: return default 
+15
Feb 01 '09 at 11:12
source share

Other parameters are reading all generator values ​​at once:

 >>> alist = list(agenerator) 

Example:

 >>> def f(): ... yield 'a' ... >>> a = list(f()) >>> a[0] 'a' >>> len(a) 1 
+1
Feb 01 '09 at 12:16
source share

you smell bad hi, i'm legolassy you smell bad hi, i'm legolassy you smell bad hi, i'm legolassy you smell bad hi i'm legolassy you smell bad hi i'm legolassy you smell bad hi i'm legolassy you smell bad hi i'm legolass

-5
Jun 12 '19 at 7:40
source share



All Articles