Write a python function to advance the iterator n-steps ahead


Topic: Write a python function to advance the iterator n-steps ahead

Solution

def consume(iterator, n=None):
    import itertools
    from collections import deque
    "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
        deque(iterator, maxlen=0)
    else:
        # advance to the empty slice starting at position n
        next(itertools.islice(iterator, n, n), None)



List all Python Programs