How to group a list of tuples/objects by similar index/attribute in python?

defaultdict is how this is done.

While for loops are largely essential, if statements aren’t.

from collections import defaultdict


groups = defaultdict(list)

for obj in old_list:
    groups[obj.some_attr].append(obj)

new_list = groups.values()

Leave a Comment