1

When you make a generator by calling a function or method that has the yield keyword in it you get an object that has a next method.

So far as I can tell, there isn't a difference between using this method and using the next builtin function.

e.g. my_generator.next() vs next(my_generator)

So is there any difference? If not, why are there two ways of calling next on a generator?

Stephen
  • 2,613
  • 1
  • 24
  • 42
  • 3
    This question may be related: http://stackoverflow.com/questions/10414210/python-why-should-i-use-next-and-not-obj-next It looks like the two exist for backward compatability reasons, but next() is the more appropriate _pythonic_ way – ctj232 Nov 21 '16 at 05:00

1 Answers1

1

In Python 2 the internal method for an iterator is next() in Python 3 it is __next__(). The builtin function next() is aware of this and always calls the right method making the code compatible with both versions. Also it adds the default argument for more easy handling of the iteration end.

Klaus D.
  • 13,874
  • 5
  • 41
  • 48