def groupby(iterable, key=None):
key, cache, elem, flag = (lambda x: x) if key is None else key, [], None, False
for i in iterable:
if cache and elem != key(i):
yield elem, cache
cache = []
elem, flag = key(i), True
cache.append(i)
if flag:
yield elem, cache