Skip to content

Instantly share code, notes, and snippets.

@0xKD
Created November 13, 2014 07:10
Show Gist options
  • Save 0xKD/86141a45fd7b66d26686 to your computer and use it in GitHub Desktop.
Save 0xKD/86141a45fd7b66d26686 to your computer and use it in GitHub Desktop.
Chunk and slice operations on lists in Python
from itertools import izip_longest
from string import lowercase
def chunk(s, size):
'''
Separates sequence into chunks of given size.
>>> chunk('helloworld', 3)
['hel', 'low', 'orl', 'd']
>>> chunk(range(20,30), 4)
[[20, 21, 22, 23], [24, 25, 26, 27], [28, 29]]
'''
chunks = len(s) // size if len(s) % size == 0 else len(s) // size + 1
return [s[i*size:i*size+size] for i in range(chunks)]
def chunk2(s, size, fillval=None):
'''
Returns iterator that will give a tuple of chunk elements on each iteration.
Optional argument fillval will be used to fill in last chunk.
>>> chunk2('helloworld', 3).next()
('h', 'e', 'l')
>>> chunk2([1, 2], 3, fillval=0).next()
(1, 2, 0)
'''
return izip_longest(*[iter(s)]*size, fillvalue=fillval)
def slicer(s, size, jump=1):
'''
Return slices of sequence with specified size and jump.
>>> slicer('12345678', 3)
['123', '234', '345', '456', '567', '678']
>>> slicer('hello', 4)
['hell', 'ello']
'''
newsize = len(s) - size + 1
return [s[i:i+size] for i in range(0, newsize, jump)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment