groupby

Bryan belred at gmail.com
Tue May 23 01:38:35 EDT 2006


George Sakkis wrote:
> Bryan wrote:
> 
>> can some explain why in the 2nd example, m doesn't print the list [1, 1, 1]
>> which i had expected?
>>
>>
>>  >>> for k, g in groupby([1, 1, 1, 2, 2, 3]):
>> ...     print k, list(g)
>> ...
>> 1 [1, 1, 1]
>> 2 [2, 2]
>> 3 [3]
>>
>>
>>  >>> m = list(groupby([1, 1, 1, 2, 2, 3]))
>>  >>> m
>> [(1, <itertools._grouper object at 0x00AAC600>), (2, <itertools._grouper object
>> at 0x00AAC5A0>), (3, <itertools._grouper object at 0x00AAC5B0>)]
>>  >>> list(m[0][1])
>> []
>>  >>>
>>
>>
>> thanks,
>>
>> bryan
> 
> I've tripped on this more than once, but it's in the docs
> (http://docs.python.org/lib/itertools-functions.html):
> 
> "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"
> 
> George
> 

i read that description in the docs so many times before i posted here. now that 
i read it about 10 more times, i finally get it.  there's just something about 
the wording that kept tripping me up, but i can't explain why :)

thanks,

bryan




More information about the Python-list mailing list