The next() function in Python is a built-in function used to retrieve the next item from an iterator. Iterators are objects that allow sequential access to elements of a collection such as a list, tuple, or string.
When next() is called, it returns the next value from the iterator. If there are no more elements left, Python raises a StopIteration exception.
The next() function is commonly used together with the iter() function, which creates an iterator from an iterable object.
next(iterator, default)
Parameters
iterator An iterator object from which the next element will be returned.
default (optional) A value that will be returned if the iterator has no more elements. If this parameter is not provided and the iterator is exhausted, Python raises a StopIteration error.
Return Value
numbers = [10, 20, 30]
it = iter(numbers)
print(next(it))
print(next(it))
print(next(it))
Output
10
20
30
Explanation
iter(numbers) creates an iterator from the list.next() retrieves the next element in the sequence.numbers = [1, 2]
it = iter(numbers)
print(next(it))
print(next(it))
print(next(it))
Output
1
2
StopIteration
Explanation
next() again raises a StopIteration exception.next() with a Default Valuenumbers = [1, 2]
it = iter(numbers)
print(next(it))
print(next(it))
print(next(it, "No more elements"))
Output
1
2
No more elements
Explanation
"No more elements" is returned.text = "ABC"
it = iter(text)
print(next(it))
print(next(it))
print(next(it))
Output
A
B
C
Explanation
next() returns the next character of the string.numbers = [5, 10, 15]
it = iter(numbers)
while True:
try:
print(next(it))
except StopIteration:
break
Output
5
10
15
Explanation
iter() and next()| Function | Purpose |
|---|---|
iter() |
Creates an iterator from an iterable |
next() |
Retrieves the next element from the iterator |
Example:
numbers = [1, 2, 3]
it = iter(numbers)
print(next(it))
Here:
numbers → iterableit → iteratornext(it) → returns next elementnext() is a built-in Python function used to retrieve the next element from an iterator.iter() function.