Splitting up a sequence

Split up a sequence in same-size(if possible) parts.


As discussed on: http://gumuz.looze.net/wordpress/index.php/archives/2005/04/20/python-chopping-up-a-sequence/

It's very straight forward:

>>> lst = [1,2,3,4,5,6,7,8,9,10]
>>> split_seq(lst,2)
[[1, 2], [3, 4], [5, 6], [7, 8], [9,10]]

It takes a list, re-groups them in another list, 2 items per group. The source list doesn't have to be evenly dividable though:

>>> lst = [1,2,3,4,5,6,7,8,9,10]
>>> split_seq(lst,3)
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

Of course, a string is a sequence too. That's what I used it for last time. I had a string of bits, which I needed to divide in pieces of 8, bytes:

>>> bits = '101011101001011010010110'
>>> split_seq(bits,8)
['10101110', '10010110', '10010110']
# Guyon Morée
# http://gumuz.looze.net/

def split_seq(seq,size):
    """ Split up seq in pieces of size """
    return [seq[i:i+size] for i in range(0, len(seq), size)]

code.activestate.com ↗