Facebook Page Twitter Page LinkedIn Page
× Python Tutorial Python Advanced Python Resources Python Libraries


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 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 below example, 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
Error!
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