next()
The built-in next()
function retrieves the next item from an iterator, raising a StopIteration
exception when the iterator is exhausted:
>>> numbers = iter([1, 2, 3])
>>> next(numbers)
1
>>> next(numbers)
2
>>> next(numbers)
3
>>> next(numbers) # Exhausted iterator
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
It can also return a default
value if the iterator is exhausted, preventing a StopIteration
exception:
>>> numbers = iter([1, 2, 3])
>>> next(numbers, "End")
1
>>> next(numbers, "End")
2
>>> next(numbers, "End")
3
>>> next(numbers, "End")
'End' # Default value
next()
Signature
next(iterator)
next(iterator, default)
Arguments
Argument | Description |
---|---|
iterator |
The iterator from which to retrieve the next item. |
default |
The value to return if the iterator is exhausted, preventing the StopIteration exception. |
Return Value
- If the iterator has remaining items,
next()
returns the next item from the iterator. - If the iterator is exhausted and a
default
is provided,next()
returns thedefault
value. - If the iterator is exhausted and no
default
is provided,next()
raises aStopIteration
exception.
next()
Examples
With an iterator as an argument:
>>> fruits_it = iter(["apple", "banana", "cherry"])
>>> next(fruits_it)
'apple'
>>> next(fruits_it)
'banana'
>>> next(fruits_it)
'cherry'
>>> next(fruits_it)
Traceback (most recent call last):
...
StopIteration
With a default
value:
>>> numbers_it = iter([10, 20])
>>> next(numbers_it, "No more items")
10
>>> next(numbers_it, "No more items")
20
>>> next(numbers_it, "No more items")
'No more items'
next()
Common Use Cases
The most common use cases for the next()
function include:
- Manually iterating over an iterator when you need to control the flow of iteration.
- Skipping the first item of an iterator, such as a header line in a CSV file.
- Providing a default value to avoid
StopIteration
exceptions when an iterator is exhausted.
next()
Real-World Example
A typical use case for next()
is reading a CSV file and skipping the header line:
with open("data.csv") as file:
next(file) # Skip the header line
for line in file:
print(line.strip())
In this example, next(file)
skips the first line of the file, which contains the headers, allowing the for
loop to process only the data lines.
next()
in Custom Classes
You can support next()
in your custom classes by implementing the .__next__()
method. Say that you want to write an iterator that takes a sequence of numbers, computes the square value of each number, and yields those values on demand. In this case, you can write the following class:
square_iter.py
class SquareIterator:
def __init__(self, sequence):
self._sequence = sequence
self._index = 0
def __iter__(self):
return self
def __next__(self):
if self._index < len(self._sequence):
square = self._sequence[self._index] ** 2
self._index += 1
return square
else:
raise StopIteration
This class takes a sequence of numbers as an argument and makes an iterator of square values. The .__next__()
method processes the current number and returns its square value. When the data is over, then .__next__()
raises the StopIteration
exception.
Related Resources
Tutorial
Iterators and Iterables in Python: Run Efficient Iterations
In this tutorial, you'll learn what iterators and iterables are in Python. You'll learn how they differ and when to use them in your code. You'll also learn how to create your own iterators and iterables to make data processing more efficient.
For additional information on related topics, take a look at the following resources:
- Reading and Writing CSV Files in Python (Tutorial)
- Python's Magic Methods: Leverage Their Power in Your Classes (Tutorial)
- Practical Recipes for Working With Files in Python (Course)
- Efficient Iterations With Python Iterators and Iterables (Course)
- Iterators and Iterables in Python: Run Efficient Iterations (Quiz)
- Reading and Writing CSV Files (Course)
- Reading and Writing CSV Files in Python (Quiz)
- Python's Magic Methods in Classes (Course)
- Python's Magic Methods: Leverage Their Power in Your Classes (Quiz)