Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic solution to drop N values from an iterator

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?

like image 410
schlamar Avatar asked Jun 20 '12 06:06

schlamar


2 Answers

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)
like image 126
John La Rooy Avatar answered Nov 07 '22 22:11

John La Rooy


You can create an iterative slice that starts at element n:

import itertools
def drop(it, n):
    return itertools.islice(it, n, None)
like image 24
ThiefMaster Avatar answered Nov 07 '22 23:11

ThiefMaster