Introduction
The next()
function is a built-in function in Python that retrieves the next item from an iterator. It takes an iterator as an argument and returns the next element from the iterator. If no more elements exist in the iterator, it will raise a StopIteration
exception. Here is an example of how to use the next()
function:
Example 1: Simple next() function
Let’s see this with the help of an example:
list = ['jhon', 'murphy', 'clark', 'ballamy']
iteration = iter(list)
next_element = next(iteration)
print(next_element)
next_element = next(iteration)
print(next_element)
next_element = next(iteration)
print(next_element)
next_element = next(iteration)
print(next_element)
Output:
jhon
murphy
clark
ballamy
Example 2: StopIteration exception
It's important to note that the next()
function will raise a StopIteration exception when there are no more elements in the iterator. Let’s see an example:
list = ['jhon', 'murphy', 'clark', 'ballamy']
iteration = iter(list)
next_element = next(iteration)
print(next_element)
next_element = next(iteration)
print(next_element)
next_element = next(iteration)
print(next_element)
next_element = next(iteration)
print(next_element)
next_element = next(iteration)
print(next_element)
Output:
jhon murphy clark ballamy Traceback (most recent call last): File "d:\upwork projects\next function\next.py", line 13, in <module> next_element = next(iteration) StopIteration
As you can see that the next()
function has raised an exception after completing the whole iteration.
Example 3: Using a while loop with the next() function
We can also iterate through all the elements using a loop. Let’s see an example:
list = ['jhon', 'murphy', 'clark', 'ballamy']
iteration = iter(list)
while True:
items = next(iteration, 'stop')
if items == 'stop':
break
print(items)
Output:
jhon
murphy
clark
ballamy
In the code snippet above, we are using a while loop along with some conditions. First of all, we are iterating through the list using the next()
function and in the next()
function, we are passing another variable stop
which will make sure that the list ends at the <i><span style="font-weight: 400;">stop</span></i>
. Then we are giving a condition that if the items reach stop
then break the loop and print out the items in the list.
References