itertools Table of Contents Overview Overview # Generates a break or new group every time the value of the key function changes [k for k, g in groupby('AAAABBBCCDAABBB')] # --> A B C D A B [list(g) for k, g in groupby('AAAABBBCCD')] # --> AAAA BBB CC D https://docs.python.org/2/library/itertools.html