Python next() Function with examples

This tutorial discusses the python next() function with examples. This is an in-built function that helps us to iterate over an iterator if the length has not been given.

next() function in Python: Syntax and uses

The syntax of next() function in python is as follows:

next( iterator, def)

The first parameter specifies the iterator over which we have to iterate. The second parameter def specifies the default value that is to be printed once we reach the end of the iteration.

The function returns the next element of the iterator. If the iterator is exhausted then it returns the default value provided in the function. If no default value is provided then it raises an exception.

Examples:

Let’s have a look at the following code.

li = [1,2,3,4]

#converting list to iterator
l=iter(li)

print(next(l,"end"))

print(next(l,"end"))

print(next(l,"end"))

print(next(l,"end"))

print(next(l,"end"))

Output:

1
2
3
4
end

In the above code, we have created a list li and then created an iterator l for it. As you can see, the next() function returns the items of the list in a sequential manner and prints “end” when all list items are exhausted.

Let’s print the elements of the list using a loop.

li = [1,2,3,4]

#converting list to iterator
l=iter(li)

while(1):
    n=next(l,"end")
    if(n!="end"):
        print(n)
    else:
        print("All list elements are printed")
        break

Output:

1
2
3
4
All list elements are printed

Now, if we omit the second parameter i.e. we do not pass the default value when iteration stops, then the program will raise an exception. See the following program.

li = [1,2]

#converting list to iterator
l=iter(li)

print(next(l))

print(next(l))

print(next(l))

The output of the above code:

1
2
Traceback (most recent call last):
File "next.py", line 10, in <module>
print(next(l))
StopIteration

You can see that since we have not provided any default value in the next() function for the end of the iteration, the above python program throws StopIteration exception as shown in the output.

Thank you.

Also, read:  Printing each item from a Python list

Leave a Reply

Your email address will not be published. Required fields are marked *