Python next() Method
The next()
method returns the next item from the iterator by calling its __next__()
method.
next() Syntax:
next(iterator, default)
Parameters:
- iterator: The iterator object created using the iter function.
- 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.
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
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.
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
1
2
3
4
5
0
0
0
0