30 seconds of python

  Back to Home



Groups the elements of a list based on the given function.

Use map() and fn to map the values of the list to the keys of an object. Use list comprehension to map each element to the appropriate key.

def group_by(lst, fn):
    return {key : [el for el in lst if fn(el) == key] for key in map(fn,lst)}