When dealing with iterators and iterables, understanding their consumption nature is crucial. In Python, an iterator can only be consumed once. This means that once you iterate over an iterator, it's exhausted and cannot be used again.
Consider the following code:
def test(data): for row in data: print("first loop") for row in data: print("second loop")
If data is a non-empty iterator (e.g., a list iterator or generator expression), the code will print "first loop" multiple times, but "second loop" will never be printed. This is because the iterator has been consumed during the first loop.
The same issue arises with other forms of iteration, such as list/set/dict comprehensions, calls to list(), sum(), or reduce(), and so on.
However, if data is another iterable such as a list or range (which are sequences), both loops will execute as expected, printing "first loop" and "second loop" for each element. This is because these iterables can be iterated over multiple times.
To reiterate, when using iterators, it's important to remember their single-consumption nature. To reuse the data, consider saving the elements to a list or using itertools.tee() to create independent iterators.
The above is the detailed content of Why Can't I Iterate Over an Iterator Twice?. For more information, please follow other related articles on the PHP Chinese website!