Be Careful Using Python Iterator
Last update: December 7, 2024 pm
Be Careful Using Python Iterator
In a recent experiment, I encountered a bug where all the results were shown as negative.
After debugging, I found that the bug was caused by using the same iterator twice.
My library API was designed to take a list of tuples as input,
but when I called it later, I passed in a map
object.
My API extracts the first and second elements of the tuple and uses them independently to obtain the experiment results. However, every time I ran the experiment, the list of second elements was empty, resulting in all negative results.
So, the key takeaway is that a Python iterator can only be consumed once!!
Reproduction
1 |
|
All blog follow CC BY-SA 4.0 licenses, please cite the creator when reprinting.