I have these two implementations to compute the length of a finite generator, while keeping the data for further processing:
def count_generator1(generator):
If you have to do this, the first method is much better - as you consume all the values, itertools.tee()
will have to store all the values anyway, meaning a list will be more efficient.
To quote from the docs:
This itertool may require significant auxiliary storage (depending on how much temporary data needs to be stored). In general, if one iterator uses most or all of the data before another iterator starts, it is faster to use list() instead of tee().