Add built in flatmap function to functools

Python already provides built in functions for functional programming paradigms like map, filter, and accumulate (using functools reduce()). However, an equally useful function flatmap is not directly offered. Of course, there are ways for a python developer to implement this on their own, as shown in here and here. But I think offering this function as a built in operator would be very helpful for new developers and help developers make more concise, elegant code.

Specifically, flatmap would take the following arguments:

flatmap([function], [list or iterable])

It would output the result of applying the function to each item in the list or iterable and then flattening the entire list.

flatmap(lambda x: [x, x, x], [1, 2, 3]) = [1, 1, 1, 2, 2, 2, 3, 3, 3]

1 Like

Is this just flatten(map(func, values))?

First, we would need to decide what the semantics of flatten are. There is a reason why Python still does not have a flatten function after 30+ years.

Fairly certain sum(map(func, values), []) would do the trick

In [1]: sum(map(lambda x: [x, x, x], [1, 2, 3]), [])
Out[1]: [1, 1, 1, 2, 2, 2, 3, 3, 3]

edit: I see this as solution in OP 2nd link…ops

I disagree. flatten requires learning and memorising a new word, one which newcomers likely haven’t encountered yet. List comprehension with nested loops can be surmised from basic examples of Python’s syntax.

flatten = itertools.chain.from_iterable

Forgot about that one.