9

Python provides list comprehensions that provide map/filter type functionality. Can I do a flatMap aka bind operation with this? I've seen solutions with itertools or other add-on libraries. Can I do this with core Python?

# this
[[x,10*x] for x in [1,2,3]]
# will result in unflattened [[1, 10], [2, 20], [3, 30]]
user2684301
  • 2,550
  • 1
  • 24
  • 33
  • `itertools` is included in the stdlib, so it is by definition "core Python." – Adam Smith Jan 28 '14 at 23:00
  • 2
    @adsmith: No, it's "Python stdlib" by definition. What OP means is as a language feature, like list comprehension syntax for `map` and `filter` – Niklas B. Jan 28 '14 at 23:02
  • 1
    "or other add-on libraries" suggests that the OP might not realize `itertools` is part of Python. – user2357112 Jan 28 '14 at 23:07
  • 1
    Just cuz I don't want to reinvent the wheel other than for purely academic purposes, what's the solution with `itertools`? – Abhijit Sarkar Jan 08 '20 at 04:10
  • See https://stackoverflow.com/questions/1077015/python-list-comprehensions-compressing-a-list-of-lists. – JP Zhang Jan 22 '21 at 00:33

2 Answers2

17
[y for x in [1, 2, 3] for y in [x, 10*x]]

Just add another for to the list comprehension.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • 7
    For clarification -- list comps are written in the same order you'd write `for` loops. First you'd do: `for x in [1,2,3]:` then indent and do `for y in [x,10*x]:`, then `yield y` or whatever you like. It still feels like backwards ordering to me (`for y in [x, 10*x] for x in [1,2,3]` makes more sense to me left-to right) but there ya have it. – Adam Smith Jan 28 '14 at 23:04
  • @adsmith: The right-to-left variant gets awkward if you add filtering with `if` – Niklas B. Jan 28 '14 at 23:05
  • Oh it makes sense either way, I just have to flip my brain sideways to see the for loops anytime I see "nested" list comprehensions like this. – Adam Smith Jan 28 '14 at 23:06
  • 3
    that works. That syntax seems illogical. A non-nested for comprehension has the source on the right and the yielded value on the left. This nesting works in the opposite order with no apparent logic to it. It will do for now regardless of elegance. – user2684301 Jan 28 '14 at 23:18
0

See python list comprehensions; compressing a list of lists?.

from functools import reduce
def flatMap(array: List[List]): List
    return reduce(list.__add__, array)
    # or return reduce(lambda a,b: a+b, array)
JP Zhang
  • 767
  • 1
  • 7
  • 27