Python next() Function
The next()
function returns the next item in an iterator.
If the items in the collection are exhausted, Python throws a StopIteration
exception.
Syntax
Python
Copy Code
next(iterator, next = None)
Parameters
Parameter | Description |
---|---|
iterator |
Required. The iteretor for which the next value should be retrieved |
next |
Optional. If provided, and if the iterator has run out of values, then next
will be returned . |
Example
Python
Copy Code
myList = ['apples', 'oranges', 'bananas'] myIter = iter(myList) # first item item = next(myIter) print(item) # second item item = next(myIter) print(item) # third item item = next(myIter) print(item) # the fourth item does not exist in myList item = next(myIter) print(item)
Output
apples oranges bananas Traceback (most recent call last): File "test.py", line 17, in <module> item = next(myIter) StopIteration
Notes
Typically iteration is handled in a for
loop. The advantage of using a
for
loop is that you don't have to handle the StopIteration
exception when the all the items
in the collection have been exhausted.
Example
Python
Copy Code
myList = ['apples', 'oranges', 'bananas'] for item in myList: print(item)Output:
apples oranges bananas
You can write write your own iterator by defining the __next__ function, which would normally be implemented as a function in a class.
Example
Python
Copy Code
class MyIterator: n = -1 def __next__(self): if (self.n == 2): raise StopIteration self.n += 1 return self.n * 5 myIterator = MyIterator() # first iteration item = next(myIterator) print(item) # second iteration item = next(myIterator) print(item) # third iteration item = next(myIterator) print(item) # fourth iteration item = next(myIterator) print(item)
Output:
0 5 10 Traceback (most recent call last): File "test.py", line 25, in <module> item = next(myIterator) File "test.py", line 6, in __next__ raise StopIteration StopIteration