Python | next method
Start your free 7-days trial now!
Python's next(~)
method returns the next item in an iterator.
Parameters
1. iterator
| iterator
The iterator for which we should return the next item.
2. default
| any
| optional
The value to return in case we have reached the end of the iterator.
Return value
The return value depends on the following cases:
Case | Return value |
---|---|
Have NOT exhausted all items in iterator | Next item in iterator |
Have exhausted all items in iterator and |
|
Have exhausted all items in iterator and no |
error |
Examples
Basic usage
To obtain the next item in the iterator test
:
a = ['hi', 'bye', 'see you']# converting the list to an iterator called testtest = iter(a)print(next(test))print(next(test))print(next(test))
hibyesee you
Note that each time we call the next(~)
method we return the next item in the iterator test
.
Default parameter
To specify default value of 'This is the default value'
:
b = ['hi', 'bye', 'see you']# converting the list to an iterator called testtest = iter(b)print(next(test, 'This is the default value'))print(next(test, 'This is the default value'))print(next(test, 'This is the default value'))print(next(test, 'This is the default value'))
hibyesee youThis is the default value
On the fourth call of the next(~)
method we return 'This is the default value'
as we have exhausted all items in the iterator test
.
StopIteration Error
If we do not provide a default
value and we reach the end of the iterator:
c = ['hi', 'bye', 'see you']# converting the list to an iterator called testtest = iter(c)print(next(test))print(next(test))print(next(test))print(next(test))
hibyesee you---------------------------------------------------------------------------StopIteration Traceback (most recent call last)<ipython-input-11-74eba8c03080> in <module> 7 print(next(test)) 8 print(next(test))----> 9 print(next(test))StopIteration:
We see that StopIteration
exception is raised as there are no more items in the iterator test
.