Skip to content

Instantly share code, notes, and snippets.

@agfor
Created April 23, 2012 22:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agfor/2474395 to your computer and use it in GitHub Desktop.
Save agfor/2474395 to your computer and use it in GitHub Desktop.
A few extra itertools-esque snippets
import collections
import itertools
def last(iterable, deque=collections.deque):
return deque(iterable, maxlen = 1)[0]
def iterlen(iterable):
return sum(1 for _ in iterable)
def droptake(iterable, takecondition, dropcondition = None,
takewhile = itertools.takewhile, dropwhile = itertools.dropwhile):
return takewhile(dropwhile(iterable,
dropcondition or (lambda item: not takecondition(item))), takecondition)
def prepend(iterable, *items):
for item in itertools.chain(items, iterable):
yield item
def append(iterable, *items):
for item in itertools.chain(iterable, items):
yield item
def skip(iterable, at_start=0, at_end=0):
it = iter(iterable)
for x in itertools.islice(it, at_start):
pass
if not at_end:
return it
queue = collections.deque(itertools.islice(it, at_end), at_end + 1)
return (queue.append(x) or queue[0] for x in it)
def reduceself(func, obj, times):
return reduce((lambda (ob, _): func(ob)), range(times), obj)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment