groupby behaviour

Discussion in 'Python' started by andrea crotti, Feb 26, 2013.

  1. 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?
     
    andrea crotti, Feb 26, 2013
    #1
    1. Advertisements

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. G?nter Jantzen

    whatsnew 2.4 about itertools.groupby:

    G?nter Jantzen, Jun 9, 2004, in forum: Python
    Replies:
    0
    Views:
    365
    G?nter Jantzen
    Jun 9, 2004
  2. Bryan

    groupby

    Bryan, May 23, 2006, in forum: Python
    Replies:
    4
    Views:
    768
    Paul McGuire
    May 27, 2006
  3. Replies:
    3
    Views:
    433
    Fredrik Lundh
    May 25, 2006
  4. Frank Millman

    "groupby" is brilliant!

    Frank Millman, Jun 13, 2006, in forum: Python
    Replies:
    20
    Views:
    2,279
    Alex Martelli
    Jun 15, 2006
  5. Roman Bertle

    groupby and itemgetter

    Roman Bertle, Oct 6, 2006, in forum: Python
    Replies:
    1
    Views:
    933
    Steven Bethard
    Oct 6, 2006
  6. 7stud

    itertools.groupby

    7stud, May 27, 2007, in forum: Python
    Replies:
    13
    Views:
    740
    =?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=
    Jun 5, 2007
  7. Steve Howell

    Re: itertools.groupby

    Steve Howell, May 27, 2007, in forum: Python
    Replies:
    13
    Views:
    688
  8. andrea crotti

    Re: groupby behaviour

    andrea crotti, Feb 26, 2013, in forum: Python
    Replies:
    1
    Views:
    180
    Paul Rubin
    Feb 26, 2013
Loading...