The next() function in Python will print out the next item of the loop. It will run until the last element of the variable.
It will return items one by one and you can add a default return value if it reaches the last element.
Here at Ibmi Media, as part of our Server Management Services, we regularly help our Customers to perform related Python function queries.
In this context, we shall look into how to use the next() function in Python.
This function prints out the next item of the iterator. You can add a default return value if it reaches the last element.
This function helps to separate elements clearly.
The syntax of next() is:
next(iterator, default)
1. Let's take the below function:
list = iter(["cat", "dog", "tiger"])
x = next(list)
print(x)
x = next(list)
print(x)
x = next(list)
print(x)
The Output will be:
cat
dog
tiger
2. add the default value:
list = iter(["cat", "dog", "tiger"])
x = next(list)
print(x)
x = next(list)
print(x)
x = next(list)
print(x)
x = next(list, "pig")
print(x)
The Output would be:
cat
dog
tiger
pig
3. Error case:
list = iter(["steak", "pizza"])
x = next(list)
print(x)
x = next(list)
print(x)
x = next(list)
print(x)
The Output:
steak
pizza
—————————————————————————
StopIteration Traceback (most recent call last)
Untitled-1 in
4 x = next(list)
5 print(x)
—-> 6 x = next(list)
7 print(x)
StopIteration:
Because the iterator has 2 values but you use the next() function 3 times.
This article covers how to use the next() function in Python. In fact, The next() function returns the next item in an iterator. You can add a default return value, to return if the iterable has reached to its end.