Python Tutorial Python Advanced Python References Python Libraries

Python next() Function



The Python next() function returns next element of the specified iterator. The function raises StopIteration exception if the iterator has reached to its end. To handle this exception, the function has one optional parameter which can be used to specify default value to return when the iterator has reached to its end.

Syntax

next(iterator, default)

Parameters

iterator Required. specify an iterator object created from iterable like list, tuple, set, and dictionary etc.
default Optional. specify default value to return when the iterable has reached to its end.

Example: using next() function

In the example below, the next() is used on iterator called MyIterator to access next element from the iterator. It raises StopIteration exception when the iterator has reached to its end.

MyList = [100, 200, 300]
MyIterator = iter(MyList)

print(next(MyIterator))
print(next(MyIterator))
print(next(MyIterator))
print(next(MyIterator))

The output of the above code will be:

100
200
300

Traceback (most recent call last):
  File "Main.py", line 7, in <module>
    print(next(MyIterator))
StopIteration

Example: using next() function with default parameter

To handle StopIteration exception, the optional parameter of next function is used to specify default value which is returned if the iterator has reached to its end.

MyList = [100, 200, 300]
MyIterator = iter(MyList)

print(next(MyIterator, "end of iterator."))
print(next(MyIterator, "end of iterator."))
print(next(MyIterator, "end of iterator."))
print(next(MyIterator, "end of iterator."))

The output of the above code will be:

100
200
300
end of iterator.

❮ Python Built-in Functions