Is there a pythonic solution to drop n
values from an iterator? You can do this by just discarding n
values as follows:
def _drop(it, n):
for _ in xrange(n):
it.next()
But this is IMO not as elegant as Python code should be. Is there a better approach I am missing here?
I believe you are looking for the "consume" recipe
http://docs.python.org/library/itertools.html#recipes
def consume(iterator, n):
"Advance the iterator n-steps ahead. If n is none, consume entirely."
# Use functions that consume iterators at C speed.
if n is None:
# feed the entire iterator into a zero-length deque
collections.deque(iterator, maxlen=0)
else:
# advance to the empty slice starting at position n
next(islice(iterator, n, n), None)
If you don't need the special behaviour when n
is None
,
you can just use
next(islice(iterator, n, n), None)
You can create an iterative slice that starts at element n
:
import itertools
def drop(it, n):
return itertools.islice(it, n, None)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With