1

I have a list that is created within an itertools.groupby operation:

def yield_unpacked_list():
    for key, grp in itertools.groupby(something_to_groupby, key=lambda x: x[0]):
        subset_of_grp = list(item[2] for item in list(grp))
        yield key, subset_of_grp

If, for example, subset_of_grp turns out to be [1, 2, 3, 4] and [5, 6, 7, 8]:

for m in yield_unpacked_list():
    print m

would print out:

('first_key', [1, 2, 3, 4])
('second_key', [5, 6, 7, 8])

Now, going back to my function definition. Obviously the following is a syntax error (the * operator):

def yield_unpacked_list():
    for key, grp in itertools.groupby(something_to_groupby, key=lambda x: x[0]):
        subset_of_grp = list(item[2] for item in list(grp))
        yield key, *subset_of_grp

I want the following result for the same print loop to be without the [list] brackets:

('first_key', 1, 2, 3, 4)
('second_key', 5, 6, 7, 8)

Note that print is only for illustrative purposes here. I have other functions that would benefit from the simplified tuple structure.

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
Kit
  • 30,365
  • 39
  • 105
  • 149

2 Answers2

5

yield (key,) + tuple(subset_of_grp)

Jack Kelly
  • 18,264
  • 2
  • 56
  • 81
2
def yield_unpacked_list():
    for key, grp in itertools.groupby(something_to_groupby, key=lambda x: x[0]):
        yield (key,) + tuple(item[2] for item in grp)

From the result you want for printing, it's clear that you want to yield a tuple -- no idea why you call it an "unpacked list" instead, but, anyway, there you are. I also removed a couple of calls to list that simply served no useful role at all in your code.

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395