What is the best way to get all but the last N elements of an iterator in Python? Here is an example of it in theoretical action:
>>> list(all_but_
This is compact (aside from consume
recipe taken from itertools
recipes) and should run at C speed:
import collections
import operator
from itertools import islice, tee
def truncate(iterable, n):
a, b = tee(iterable)
consume(b, n)
return map(operator.itemgetter(0), zip(a, b))
# From itertools recipes
def consume(iterator, n=None):
"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)