You could use a collections.defaultdict
:
from collections import defaultdict
out = defaultdict(list)
for e in mylist:
out[f(e)].append(e)
Now as long as f(e)
is hashable for all appropriate values of e
, you will get an output like
defaultdict(<class 'list'>, {0: [2, 4, 6], 1: [1, 3, 5]})
If you want a list of these sub-lists, you can then do:
sublists = list(out.values())
However note that dictionaries aren't guaranteed to retain a sensible order; each sublist will remain ordered, but you could get
[[2, 4, 6], [1, 3, 5]]
or
[[1, 3, 5], [2, 4, 6]]
in this example.
The long-form equivalent to show what defaultdict
does:
out = {}
for e in mylist:
key = f(e)
if key not in out:
out[key] = []
out[key].append(e)