Search code examples
pythongroup-byyieldpython-itertoolsiterable-unpacking

How do I yield a pre-unpacked list?


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.


Solution

  • yield (key,) + tuple(subset_of_grp)