Search code examples
pythongroup-bypython-itertools

No values appearing in itertools groupby - python


I am trying to group values in a string using python - itertools.groupby. I have tried using this code:

for key,values in itertools.groupby(s):
    print(key,list(values))

And I get this output:

a ['a']
b ['b']
a ['a', 'a']
b ['b', 'b', 'b']
c ['c']

which is fine. But when I add an if condition and change the code to in this way:

out = ''
for key,values in itertools.groupby(s):
    if len(list(values))==1:
        out+=key
    else:
        out += key
        out += str(len(list(values)))
    print(key,list(values))

I get this output:

a []
b []
a []
b []
c []

I don't know why the lists are being empty


Solution

  • values is an iterator, you can only call list() on it once before it's used up. You should save that result in a variable & reuse it.

    out = ''
    for key,values in itertools.groupby(s):
        value_list = list(values)  # values iterator exhausted here, can't use it again
        if len(value_list)==1:
            out+=key
        else:
            out += key
            out += str(len(value_list))
        print(key,value_list)