0

This might not be the perfect example (i know this is easier to do with list comprehension), but is there a way to unpack the child list created from split() at the time of its creation in lambda function if we were to use map method? Please also don't add a separate function outside map just to flat the list.

data = ['oh my god','that is','super duper']
list(map(lambda i: i.split(), data))
>>> [['oh', 'my', 'god'], ['that', 'is'], ['super', 'duper']]

expected result is a flattened list like this. ['oh', 'my', 'god', 'that', 'is', 'super', 'duper']

somniumm
  • 115
  • 1
  • 10
  • 1
    Not with `list(map(lambda..., data))`. `map` always gives you the same number of elements you put in. You can get the output you want with a list comprehension, which you already seem to know. – khelwood Nov 08 '21 at 16:01
  • i see.. it seems in js you can do something like [ ...[], ...[], ...[] ] – somniumm Nov 08 '21 at 16:03
  • Just use a list-comprehension to do a flat-map operation, `[s for string in data for s in string.split()]` – juanpa.arrivillaga Nov 08 '21 at 17:29
  • Alternatively, `from collections import chain` then `list(chain.from_iterable(map(lambda i: i.split(), data)))` – juanpa.arrivillaga Nov 08 '21 at 17:30

1 Answers1

-2

A bit of a "hacky" solution but this will work

sum(list(map(lambda i: i.split(), data)), [])
Mortz
  • 4,654
  • 1
  • 19
  • 35
  • hahah it's cute but yes very hacky.. i was looking for an elegant one – somniumm Nov 08 '21 at 16:08
  • also interesting question: why doesn't it produce [[result]]? b/c essentially it does internally is add [a]+ [b]+ [] together and there is still the outer [] created from list() function?? – somniumm Nov 08 '21 at 16:15
  • For the same reason that `sum([1, 2, 3], 7)` produces 13 and not `[13]`. The result is effectively `[] + ['a'] + ['b']` – Mortz Nov 08 '21 at 17:24
  • Don't use this, this is a well-known anti-pattern, and it is using the `sum` built-in in ways specifically warned against in the documentation. It is O(N^2) when it is trivial to do this in `O(N)` – juanpa.arrivillaga Nov 08 '21 at 17:28
  • @somniumm that `list` is actually superfluous – juanpa.arrivillaga Nov 08 '21 at 17:28