Python 2.6 introduced a next
function.
Why was this necessary? One could always type obj.next()
instead of next(obj)
.
Is the latter more pythonic
?
Definition and Usage. The next() function returns the next item in an iterator. You can add a default return value, to return if the iterable has reached to its end.
Python next() function is used to fetch next item from the collection. It takes two arguments an iterator and a default value and returns an element.
PEP 3114 describes this change. An excerpt about the motivation:
This PEP proposes that the
next
method be renamed to__next__
, consistent with all the other protocols in Python in which a method is implicitly called as part of a language-level protocol, and that a built-in function namednext
be introduced to invoke__next__
method, consistent with the manner in which other protocols are explicitly invoked.
Be sure to read this PEP for more interesting details.
As for why you want to use the next
built-in: one good reason is that the next
method disappears in Python 3, so for portability it's better to start using the next
built-in as soon as possible.
next(iterator[, default])
Retrieve the next item from the iterator by calling its
next()
(__next__()
in python 3) method. If default is given, it is returned if the iterator is exhausted, otherwiseStopIteration
is raised.
You get the default
option.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With