Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If i uncomment the print() function in the for loop, the 'groups' list is getting populated with empty lists instead of results

import itertools

data1 =[100,80,80,80,80,80,90,90,85,85,85]
keys = []
groups = []
sorted_data1 = sorted(data1)

for k,g in itertools.groupby(sorted_data1):
    #print('key: ',k,' group: ',list(g))
    keys.append(k)
    groups.append(list(g))

print('keys: ', keys)
print('Groups: ', groups)

RESULT OF ABOVE CODE:

keys:  [80, 85, 90, 100]
Groups:  [[80, 80, 80, 80, 80], [85, 85, 85], [90, 90], [100]]

RESULT I GET WHEN 'print()' IS UNCOMMENTED:
key:  80  group:  [80, 80, 80, 80, 80]
key:  85  group:  [85, 85, 85]
key:  90  group:  [90, 90]
key:  100  group:  [100]
keys:  [80, 85, 90, 100]
Groups:  [[], [], [], []]

Un-commenting print() in for-loop is giving 'groups' as list of empty lists. Please look into it.

like image 920
Vineeth T Sunny Avatar asked Dec 06 '25 04:12

Vineeth T Sunny


1 Answers

In the loop

for k,g in itertools.groupby(sorted_data1):

g is itself an iterator, it's not a collection like a list.

When you call

print('key: ',k,' group: ',list(g))

inside the loop, the list(g) inside the print already goes through the entire iterator g to create the list. So, when you call

groups.append(list(g))

afterwards, g is already "empty" in some sense (more precisely: it is pointing to the end of the iterator), so there's nothing left to put in the list anymore


Like DDGG suggested, you can store the results of iterating through g once in a more permanent collection (like a list) first. Then you can re-use that list multiple times

like image 139
Dennis Soemers Avatar answered Dec 07 '25 20:12

Dennis Soemers