Splitting a list

Jeff Epler jepler at unpythonic.net
Tue Aug 31 10:11:37 EDT 2004


Here's my version as a generator function:
    def split(it, elem):
        l = []
        for i in it:
            if i == elem:
                yield l
                l = []
            else:
                l.append(i)
        yield l

>>> list(split(" a b c ", " "))
[[], ['a'], ['b'], ['c'], []]
>>> " a b c ".split(" ")
['', 'a', 'b', 'c', '']
>>> l = [1,2,3,-1,4,5,-1,8,9]
>>> list(split(l, -1))
[[1, 2, 3], [4, 5], [8, 9]]

Jeff
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20040831/01370557/attachment.sig>


More information about the Python-list mailing list