Issue 33681: itertools.groupby() returned igroup is only callable once (original) (raw)
Hello,
So i discovered a small unusual behavior (tracking it down was time-consuming) when using itertools.groupby(), i have checked the documentation and it states that:
"The returned group is itself an iterator that shares the underlying iterable with groupby(). Because the source is shared, when the groupby() object is advanced, the previous group is no longer visible. So, if that data is needed later, it should be stored as a list"
I do agree with this statement, though i believe a call to igroup successively in the same iteration should yield the same result while now it returns the correct igroup in the first call while the following call returns an empty list.
Here's a small code snippet that illustrates this behavior:
Code:
import itertools
mylist = [(1,2), (1,3), (2,5)]
for key, igroup in itertools.groupby(mylist, lambda x: x[0]): print(list(igroup)) # prints the expected igroup print(list(igroup)) # prints an empty list print(list(igroup)) # prints an empty list
Output:
[(1, 2), (1, 3)] [] [] [(2, 5)] [] []
Thanks in advance for anyone who works on this issue
This is standard behaviour for all iterators. Once you have iterated over them once, they are consumed, and iterating over them again returns nothing:
py> it = iter("abc") py> print(list(it)) ['a', 'b', 'c'] py> print(list(it)) []