DEV Community

Cover image for Python next() function
libertycodervice
libertycodervice

Posted on

3

Python next() function

In this article we'll discuss the Python next() function. The Python next() function returns an iterator to the next item. If you have an iterable, it makes sense to use the next() function.

The next() syntax is:

next (iterator [, default])

Where the parameters are:

  • Iterator: iterables
  • Default: optional, used to set the default return value when there is no next element, if not set, and no next element is found it triggers the StopIteration exception.

The function return the current object in the iteratable.

examples

The following example shows how to use the next of:

#!/usr/bin/python
#-*- coding: UTF-8 -*-

# First get Iterator object:
it = iter ([1, 2, 3, 4, 5])

# Cycle:
while True:
    try:
        # Get the next value:
        x = next(it)
        print(x)
    except StopIteration:
        # Encounter StopIteration loop exits
        break

The output is:

    1
    2
    3
    4
    5

It raises a StopIteration exception that you must catch, because otherwise the program stops abruptly (an exception is an 'error' that occurs while the program is running).

>>> 
>>> nums = [1,2,3,4,5,6]
>>> it = iter(nums)
>>> while True:
...     x = next(it)
...     print(x)
... 
1
2
3
4
5
6
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
StopIteration
>>> 

So catch the StopIteration exception with a try-except block.

>>> nums = [1,2,3,4,5,6]
>>> it = iter(nums)
>>> while True:
...     try:
...         x = next(it)
...         print(x)
...     except StopIteration:
...         break
... 

Related links:

Image of Quadratic

Free AI chart generator

Upload data, describe your vision, and get Python-powered, AI-generated charts instantly.

Try Quadratic free

Top comments (0)

πŸ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay