If you just want the groups, without the keys, you need to realize the group generators as you go, per the docs:
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.
This means that when you try to list
-ify the groupby
generator first using ll = list(g)
, before converting the individual group generators, all but the last group generator will be invalid/empty.
(Note that list
is just one option; a tuple
or any other container works too).
So to do it properly, you'd make sure to list
ify each group generator before moving on to the next:
from operator import itemgetter # Nicer than ad-hoc lambdas
# Make the key, group generator
gen = groupby(things, key=itemgetter(0))
# Strip the keys; you only care about the group generators
# In Python 2, you'd use future_builtins.map, because a non-generator map would break
groups = map(itemgetter(1), gen)
# Convert them to list one by one before the next group is pulled
groups = map(list, groups)
# And listify the result (to actually run out the generator and get all your
# results, assuming you need them as a list
groups = list(groups)
As a one-liner:
groups = list(map(list, map(itemgetter(1), groupby(things, key=itemgetter(0)))))
or because this many map
s gets rather ugly/non-Pythonic, and list comprehensions let us do nifty stuff like unpacking to get named values, we can simplify to:
groups = [list(g) for k, g in groupby(things, key=itemgetter(0))]