Python next() function

libertycodervice

libertycodervice

Posted on March 2, 2020

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:

💖 💪 🙅 🚩
libertycodervice
libertycodervice

Posted on March 2, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Learning Python
javascript Learning Python

November 28, 2024

Calculate savings with Python!
beginners Calculate savings with Python!

November 26, 2024

UV the game-changer package manager
programming UV the game-changer package manager

November 24, 2024

Beginners Guide for Classes
python Beginners Guide for Classes

November 20, 2024