I am working on a task that requires that I use an iterator multiple times. For example
#data
fruit= ("grape", "banana", "apple")
#iterator
myit = iter(fruit)
#the function I have
def printIter(its):
for x in its:
print(x)
def printIter2(its):
for x in its:
print(x)
I have to call printIter
on the iterator twice but it is to perform completely different functions. But an iterator can only be consumed once.
I don't have control over the data source fruit
and iterator myit
. I only have control over the functions printIter()
.
How best can I achieve my aim using less memory.
What i currently have:
it1, it2 = itertools.tee(its)
printIter(it1)
printIter(it2)
del it1, it2
Is this a good practice, any other way?
itertools.tee
: "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 uselist()
instead oftee()
."iter
in the first place, instead of usingfruit
directly? Thefor
loop is implicitly callingiter
onits
, even if it is already an iterator.iter
but from the structure of the code, that is what is happening. I am to just consume the iterator.del it1, it2
? It's pointless. Anyway,tee
is good of you use part of the results then need to start consuming again, if you are going to consume the whole thing once then need to do it again, you might as well just uselist