Skip to content

Instantly share code, notes, and snippets.

@michilu
Created August 12, 2012 00:56
Show Gist options
  • Save michilu/3328359 to your computer and use it in GitHub Desktop.
Save michilu/3328359 to your computer and use it in GitHub Desktop.
Iteration over list slices
from itertools import chain, islice
def divide(sequence, size):
"""
>>> [i for i in divide(range(10), 3)]
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
>>> [i for i in divide('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 3)]
['ABC', 'DEF', 'GHI', 'JKL', 'MNO', 'PQR', 'STU', 'VWX', 'YZ']
"""
i = 0
while sequence[i:i+1]:
yield sequence[i:i+size]
i += size
def idivide(iterable, size):
"""
>>> [list(i) for i in idivide(iter(xrange(10)), 3)]
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
>>> ["".join(list(i)) for i in idivide(iter('ABCDEFGHIJKLMNOPQRSTUVWXYZ'), 3)]
['ABC', 'DEF', 'GHI', 'JKL', 'MNO', 'PQR', 'STU', 'VWX', 'YZ']
"""
while True:
yield chain([iterable.next()], islice(iterable, size-1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment