For picking just one element of a generator use
break in a
for statement, or
According to your example (literally) you can do something like:
for my_element in myfunct():
If you want “get just one element from the [once generated] generator whenever I like” (I suppose 50% thats the original intention, and the most common intention) then:
gen = myfunct()
for my_element in gen:
This way explicit use of
generator.next() can be avoided, and end-of-input handling doesn’t require (cryptic)
StopIteration exception handling or extra default value comparisons.
for statement section is only needed if you want do something special in case of end-of-generator.
In Python3 the
.next() method was renamed to
.__next__() for good reason: its considered low-level (PEP 3114). Before Python 2.6 the builtin function
next() did not exist. And it was even discussed to move
next() to the
operator module (which would have been wise), because of its rare need and questionable inflation of builtin names.
next() without default is still very low-level practice – throwing the cryptic
StopIteration like a bolt out of the blue in normal application code openly. And using
next() with default sentinel – which best should be the only option for a
next() directly in
builtins – is limited and often gives reason to odd non-pythonic logic/readablity.
Bottom line: Using next() should be very rare – like using functions of
operator module. Using
for x in iterator ,
list(iterator) and other functions accepting an iterator seamlessly is the natural way of using iterators on application level – and quite always possible.
next() is low-level, an extra concept, unobvious – as the question of this thread shows. While e.g. using
for is conventional.