I would like to loop over a "slice" of an iterator. I'm not sure if this is possible as I understand that it is not possible to slice an iterator. What I would like to do is this:
def f(): for i in range(100): yield(i) x = f() for i in x[95:]: print(i) This of course fails with:
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-37-15f166d16ed2> in <module>() 4 x = f() 5 ----> 6 for i in x[95:]: 7 print(i) TypeError: 'generator' object is not subscriptable Is there a pythonic way to loop through a "slice" of a generator?
Basically the generator I'm actually concerned with reads a very large file and performs some operations on it line by line. I would like to test slices of the file to make sure that things are performing as expected, but it is very time consuming to let it run over the entire file.
Edit:
As mentioned I need to to this on a file. I was hoping that there was a way of specifying this explicitly with the generator for instance:
import skbio f = 'seqs.fna' seqs = skbio.io.read(f, format='fasta') seqs is a generator object
for seq in itertools.islice(seqs, 30516420, 30516432): #do a bunch of stuff here pass The above code does what I need, however is still very slow as the generator still loops through the all of the lines. I was hoping to only loop over the specified slice
itertools.islice?islice-ing the generator won't stop it from going through the lines before the ones you care about and processing them. It'd be better to provide it with anisliceof the file. (You'll still need to read the file to look for newlines, but you'll skip whatever processing the generator does on the unwanted lines.)