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?
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']
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With