How to Use the Python next() Function

09/12/2021

Contents

In this article, you will learn how to use the Python next() function.

Python next() Function

The next() function in Python is used to get the next item from an iterable object. An iterable object is any object in Python that can be looped over using a for loop or can be iterated over using the iter() function. Examples of iterable objects in Python include lists, tuples, sets, and dictionaries.

The next() function takes one argument, which is the iterable object that you want to get the next item from. It returns the next item in the iterable.

Here is an example of how to use the next() function with a list:

my_list = [1, 2, 3, 4, 5]
my_iterator = iter(my_list)

# Get the first item from the iterator
print(next(my_iterator)) # Output: 1

# Get the next item from the iterator
print(next(my_iterator)) # Output: 2

In this example, we created a list called my_list and then created an iterator from that list using the iter() function. We then used the next() function to get the first item from the iterator, which is 1. We then used the next() function again to get the next item from the iterator, which is 2.

It’s important to note that if you call the next() function when there are no more items in the iterable object, a StopIteration exception will be raised. Therefore, you should always handle this exception when using the next() function in your code. Here is an example of how to do this:

my_list = [1, 2, 3, 4, 5]
my_iterator = iter(my_list)

try:
    # Get the first item from the iterator
    print(next(my_iterator)) # Output: 1

    # Get the next item from the iterator
    print(next(my_iterator)) # Output: 2

    # Try to get the next item, but there are no more items in the iterator
    print(next(my_iterator))

except StopIteration:
    # Handle the StopIteration exception
    print("No more items in the iterator.")

In this example, we added a try and except block to handle the StopIteration exception. When we try to get the next item from the iterator after the last item has been returned, the StopIteration exception is raised, and the code in the except block is executed, which prints “No more items in the iterator.”