groupby behaviour

andrea crotti andrea.crotti.0 at gmail.com
Tue Feb 26 17:27:43 CET 2013


So I was trying to use groupby (which I used in the past), but I
noticed a very strange thing if using list on
the result:

In [109]: s = sorted(s, key=keyfunc)

In [110]: s
Out[110]: [(1, 2), (1, 3), (1, 5), (2, 3)]


In [117]: m2 = list(groupby(s, keyfunc))

In [118]: for name, res in m2:
   .....:     for r in res:
   .....:         print name, r
   .....:
2 (2, 3)

In [119]: m2 = groupby(s, keyfunc)

In [120]: for name, res in m2:
    for r in res:
        print name, r
   .....:
1 (1, 2)
1 (1, 3)
1 (1, 5)
2 (2, 3)

How is that possible?
Generating the list first should be the same as iterating after, how
can it behave differently?



More information about the Python-list mailing list