How to create a copy of python iterator? [duplicate] How to create a copy of python iterator? [duplicate] python-3.x python-3.x

How to create a copy of python iterator? [duplicate]


Use the itertools.tee() function to produce copies; these use a buffer to share results between different iterators:

from itertools import teemy_list = [5, 4, 3,2]first_it = iter(my_list)first_it, second_it = tee(first_it)print next(first_it)   # prints 5print next(second_it)  # prints 5print next(first_it)   # prints 4

Note that you should no longer use the original iterator; use only the tees.

Note that the buffer also means that these can incur a significant memory cost if you advance one of the copies far ahead of the others! From the documentation:

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().