How to create a copy of python iterator?

In python, I tried to create a copy of my iterator using the destination, but it created a copy of the iterator that references the original iterator. For instance:

my_list = [5, 4, 3,2] first_it = iter(my_list) second_it = first_it print next(first_it ) #it will print 5 print next(second_it) #it will print 4 print next(first_it ) #it will print 3 

As you see in the example, first_it and second_it both belong to the same fighter. Is it possible to create a copy of an iterator object that is not related to the original object?

Note This question is about creating a copy of the iterator object by value. Therefore, do not call for item in my_list: similar solutions. thanks in advance

+6
source share
1 answer

Use the itertools.tee() function to create copies; they use a buffer to exchange results between different iterators:

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

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

Note that a buffer also means that they can incur a significant memory cost if you move 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 starting another iterator, it is faster to use list() instead of tee() .

+9
source

Source: https://habr.com/ru/post/1014831/


All Articles