{"@context":"https://schema.org","@type":"Article","mainEntityOfPage":{"@type":"WebPage","@id":"https://www.tutorialsteacher.com/python/next-method"},"headline":"Python next() Method","author":{"@type":"Organization","name":"TutorialsTeacher","url":"https://www.tutorialsteacher.com/aboutus"},"publisher":{"@type":"Organization","name":"TutorialsTeacher","logo":{"@type":"ImageObject","url":"https://www.tutorialsteacher.com/Content/images/logo.svg"},"sameAs":["https://www.facebook.com/tutorialsteacher","https://twitter.com/tutorialstchr","https://www.youtube.com/@tutorialsteacherOfficial"]},"dateModified":"2021-06-26T15:03:44.2052932Z","description":"The next() method returns the next item from the iterator by calling its __next__() method."}__next__() method." />

Python next() Method

The next() method returns the next item from the iterator by calling its __next__() method.

next() Syntax:

next(iterator, default)

Parameters:

  1. iterator: The iterator object created using the iter function.
  2. default: (Optional) The default value to return if an iterator is exhausted.

Return Value:

Returns the next value from the iterator. If already return last value then returns the specified default value and if no default value specified, raises StopIteration error.

The following example retrieves items from the iterator using the next() method.

Example:
nums = [1,2,3,4,5]
numitr = iter(nums)

print(next(numitr)) # prints 1
print(next(numitr)) # prints 2
print(next(numitr)) # prints 3
print(next(numitr)) # prints 4
print(next(numitr)) # prints 5
print(next(numitr)) # raise StopIteration error

Output
1
2
3
4
5
Traceback (most recent call last):
File "<pyshell#152>", line 1, in <module>
print(next(numitr))
StopIteration

Above, calling next(numitr) after returning all the values from the collection raises StopIteration error. To avoid this error, a default value can be passed as an arguement.

Example:
nums = [1,2,3,4,5]
numitr = iter(nums)

print(next(numitr, 0)) # prints 1
print(next(numitr, 0)) # prints 2
print(next(numitr, 0)) # prints 3
print(next(numitr, 0)) # prints 4
print(next(numitr, 0)) # prints 5
print(next(numitr, 0)) # prints 0
print(next(numitr, 0)) # prints 0
print(next(numitr, 0)) # prints 0
print(next(numitr, 0)) # prints 0
Output
1
2
3
4
5
0
0
0
0
Want to check how much you know Python?