How to turn an itertools "grouper" object into a list
18:54 11 Jun 2017

I am trying to learn how to use itertools.groupby in Python and I wanted to find the size of each group of characters. At first I tried to see if I could find the length of a single group:

from itertools import groupby
len(list(list( groupby("cccccaaaaatttttsssssss") )[0][1]))

and I would get 0 every time.

I did a little research and found out that other people were doing it this way:

from itertools import groupby
for key,grouper in groupby("cccccaaaaatttttsssssss"):
    print key,len(list(grouper))

Which works great. What I am confused about is why does the latter code work, but the former does not? If I wanted to get only the nth group like I was trying to do in my original code, how would I do that?

python python-itertools