I recently had to debug some code that went something like this:
for key, group in itertools.groupby(csvGrid, lambda x: x[0]):
value1 = sum(row[1] for row in group)
value2 = sum(row[2] for row in group)
results.append([key, value1, value2])
In every result set, value2
came out as 0
. When I looked into it, I found that the first time the code iterated over group
, it consumed it, so that the second time there were zero elements to iterate over.
Intuitively, I would expect group
to be a list which can be iterated over an indefinite number of times, but instead it behaves like an iterator which can only be iterated once. Is there any good reason why this is the case?