Iterate over an iterable multiple times
I was working on a piece of code today and I need to iterate over a iterable multiple times to do some computes. The body of code is the same for all passes. One obvious thing I can do is to do double loops:
results = []
for t in range(n_repeats):
for item in get_iterable():
results.append(f.process(item))
The reason that I need to loop over it multiple times rather than loop once and duplicate results
is that f
has an internal state, it gives a different output based on the number of times it has seen the input. The above code did work, but not as nice as I’d like. I utilized chain
and repeat
from itertools
to clean up it a bit:
from itertools import chain, repeat
results = []
for item in chain(*repeat(get_iterable(), n_repeats)):
results.append(f.process(item))
It does the exactly same thing, but the code reads more like straight English.