Lin Ma Lin Ma - 1 month ago 9
Python Question

Python generator next method

For the

next
method of generator, I use the below example. I tried to find the Python documentation for
next
method, but failed, could anyone help to point out?

The purpose I want to find the official document is I want to look for all forms of
next
methods and meaning of the 2nd parameter
None
in my below example.

slice = (x**2 for x in range(0,100))
first = next(slice, None)
print first
for item in slice:
print item

Answer

next() is a function, so it is listed in the functions documentation:

next(iterator[, default])
Retrieve the next item from the iterator by calling its __next__() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.

The second argument then is the default, returned if iterator.__next__() raised StopIteration. If no default is set, the StopIteration exception is not caught but propagated:

>>> def gen():
...     yield 1
...
>>> g = gen()
>>> next(g, 'default')
1
>>> next(g, 'default')
'default'
>>> g = gen()
>>> next(g, 'default')
1
>>> next(g)  # no default
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

The default is rather redundant for the specific example you gave, as the (x**2 for x in range(0,100)) generator expression is guaranteed to have at least one result.

PyCharm can show you documentation for Python standard-library functions; just use the Quick Documentation feature (CTRL-Q).

Comments