Python next()
Python next() builtin function is used to get the next item from the given iterator object.
In this tutorial, we will learn about the syntax of Python next() function, and learn how to use this function with the help of examples.
Syntax
The syntax of next() function is
next(iterator[, default])
where
Parameter | Required/ Optional | Description |
---|---|---|
iterator | Required | An iterator object. |
default | Optional | Default value if the next item is not available. |
Returns
The function returns the item.
Examples
1. Next Item of Iterator
In this example, we take a list, get the iterator for this list, and call next function with this iterator passed as argument.
Python Program
x = ['apple', 'banana', 'cherry']
iterator = iter(x)
print(next(iterator))
print(next(iterator))
Output
apple
banana
2. No Next Item of Iterator
In this example, we take a list, get the iterator for this list, and call next function many times more than the items in the iterator. If there is no next item available, then interpreter raises StopIteration.
Python Program
x = ['apple', 'banana', 'cherry']
iterator = iter(x)
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
Output
pple
banana
cherry
Traceback (most recent call last):
File "/Users/tutorialkart/Desktop/Projects/PythonTutorial/Example.py", line 6, in <module>
print(next(iterator))
StopIteration
3. Next Item of Iterator with Default Value
If we provide default value to next(), and if next item is not available in the iterator, then next() returns the default value.
Python Program
x = ['apple', 'banana', 'cherry']
iterator = iter(x)
print(next(iterator, "nothing"))
print(next(iterator, "nothing"))
print(next(iterator, "nothing"))
print(next(iterator, "nothing"))
Output
apple
banana
cherry
nothing
Conclusion
In this Python Tutorial, we have learnt the syntax of Python next() builtin function, and also learned how to use this function, with the help of Python example programs.