Let us suppose that I have a list in Python, that can be quite long: mylist = [{"a": 2}, {"a": 4}, {"b": 3}, {"a": 3}, ..., {"a": 5}] I have have a function that for each element return a "group" (None when the element is in no group) def get_group(element): a_value = element.get("a", None) if a_value is not None: return "EVEN" if a_value % 2 == 0 else "ODD" return None I am searching for a concise, pythonic and algorithmcally-efficient way of implementing that. I have a first version below. Is there any function or data-structure in the Python standard lib that would help me implement this in a more concise way without sacrifice to the algorithmic complexity? def get_first_n_by_group(list_, n, group_function, n_groups): trimmed_list = list() max_elements = n * n_groups nb_elements_per_group = defaultdict(int) for element in list_: group = group_function(element) if group is not None and nb_elements_per_group[group] < n: trimmed_list.append(element) nb_elements_per_group[group] += 1 if len(trimmed_list) == max_elements: break return trimmed_list Continue reading...