15

I noticed that Python2.6 added a next() to it's list of global functions.

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.

What was the motivation for adding this? What can you do with next(iterator) that you can't do with iterator.next() and an except clause to handle the StopIteration?

jamylak
  • 128,818
  • 30
  • 231
  • 230

3 Answers3

18

It's just for consistency with functions like len(). I believe next(i) calls i.__next__() internally.

See http://www.python.org/dev/peps/pep-3114/

SilentGhost
  • 307,395
  • 66
  • 306
  • 293
Steve Mc
  • 211
  • 1
  • 2
  • +1. The same reason Python has a built-in len() function. See the accepted answer to http://stackoverflow.com/questions/83983/why-isnt-the-len-function-inherited-by-dictionaries-and-lists-in-python for the link to Guido's rationale. – Van Gale Mar 17 '09 at 22:01
10

Note that in Python 3.0+ the next method has been renamed to __next__. This is because of consistency. next is a special method and special methods are named by convention (PEP 8) with double leading and trailing underscore. Special methods are not meant to be called directly, that's why the next built in function was introduced.

Manuel Ceron
  • 8,268
  • 8
  • 31
  • 38
0

It calls __next__ internally, but it makes it look more 'functional' than 'object-oriented'. Mind you that's just my opinion, but I don't like next(i) rather than i.next(). But as Steve Mc said, it also helps slightly with consistency.

SilentGhost
  • 307,395
  • 66
  • 306
  • 293
fengshaun
  • 2,100
  • 1
  • 16
  • 25