How to use Python next() function? [SOLVED]


Written By - Nisar Ahmad
Advertisement

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:

Advertisement
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

next() function

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment