Lin Ma Lin Ma - 1 year ago 167
Python Question

Python generator next method

For the

method of generator, I use the below example. I tried to find the Python documentation for
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
methods and meaning of the 2nd parameter
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 Source

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')
>>> next(g, 'default')
>>> g = gen()
>>> next(g, 'default')
>>> next(g)  # no default
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>

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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download