Search code examples
pythonrun-length-encoding

Groupby object disappears after list operation


I am trying the run-length encoding problem, and after running a groupby & list operation, my groupby object somehow disappeared.

import itertools
s = 'AAAABBBCCDAA'
for c, group in itertools.groupby(s):
    print(list(group))
    print(list(group))

My output is

['A', 'A', 'A', 'A']
[]
['B', 'B', 'B']
[]
['C', 'C']
[]
['D']
[]
['A', 'A']
[]

so for each loop, the 2 print commands yield different results.

Can anybody help to explain what I did wrong?


Solution

  • Because there generators, after they're used they're gone:

    >>> a = iter([1, 2, 3])
    >>> list(a)
    [1, 2, 3]
    >>> list(a)
    []
    

    To keep them:

    import itertools
    s = 'AAAABBBCCDAA'
    for c, group in itertools.groupby(s):
        l = list(group)
        print(l)
        print(l)
    

    Output:

    ['A', 'A', 'A', 'A']
    ['A', 'A', 'A', 'A']
    ['B', 'B', 'B']
    ['B', 'B', 'B']
    ['C', 'C']
    ['C', 'C']
    ['D']
    ['D']
    ['A', 'A']
    ['A', 'A']