You need to make sure that g elements are consumed only once:
>>> print [(len(list(g)), k) if len(list(g)) > 1 else k for k, g in ((k, list(g)) for k, g in groupby(a))] [(3, 'a'), 'b', (2, 'd'), (3, 'c')]
This code will also k, g in groupby(a) over k, g in groupby(a) , but it will turn g into a list object. The rest of the code can access g as many times as necessary (to check the length) without consuming the results.
Before making this change, g was an itertools._grouper object, which means you can iterate over g only once. After that, it will be empty, and you cannot repeat it again. This is why you see a length of 0 in the results.
source share