I'm using a library that returns a generator. Is there a way to start at a particular iteration without using multiple next () statement?
In a simple for loop, I could do the following.
array = [2, 5, 1, 4, 3]
for i in array [2:]:
# do something
In a generator, I couldn't do as shown above. Instead I'll have to use multiple next () statements to start at the 3rd index. When attempting to do the same as the for loop, I get an error that said, "generator is not scriptable."
itertools.islice
does this, but in reality, it's just invokingnext
for you over and over (though at the C layer in CPython, so it's faster than doing it manually).Yes, you can use
itertools.islice()
, which can slice the generator as you want -Please note, though you are not manually doing the multiple
next()
, it is being internally done byislice()
. You cannot reach at the required index until you iterate till it (islice just does that for you , instead of you have to write multiplenext()
, etc).The signature of
itertools.islice
is -The first argument is always the iterable, then if you pass in only 2 arguments, second argument is interpreted as the
stop
index (exclusive, meaning it does not return thestop
index element).If there are 3 or 4 arguments to it , second argument is treated as the start index (index) , third argument as the
stop
(exclusive) , and if fourth argument is specified its treated as thestep
value.