Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 322
Bao Le Avatar asked Jun 28 '19 03:06

Bao Le


2 Answers

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']
like image 151
U12-Forward Avatar answered Nov 05 '22 10:11

U12-Forward


The groupby function returns an iterator which is consumed upon your call to list(group).

"The returned group is itself an iterator that shares the underlying iterable with groupby(). Because the source is shared, when the groupby() object is advanced, the previous group is no longer visible." docs.

like image 38
Calvin Warner Avatar answered Nov 05 '22 10:11

Calvin Warner