Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

7
  • 1
    Just to be explicit, this means that the one-level flatten function can be defined as lambda z: [x for y in z for x in y]. Commented Apr 16, 2015 at 9:24
  • 1
    "A general purpose flattener needs some way to be told what is atomic and what can be further subdivided.": This sounds like a problem that can be solved using OOP: each object could have a flatten method. The implementation of this method should recursively call flatten on its subcomponent, if the object is a composite. Unfortunately, AFAIK not every value is an object in Python. In Ruby it should work though. Commented Sep 28, 2015 at 11:54
  • 1
    a flatten helper for a one-level flatten rather than a continued "for in for in" is already a good enough case IMO. easily readable Commented Jun 15, 2016 at 22:01
  • 2
    @Giorgio Python shies away from such methods. Protocols are preferred, and I find they're vastly smoother to work with than an OOP design since you often don't even need to implement very much at all. Commented Dec 13, 2017 at 22:58
  • @Giorgio Having a flatten method only moves the problem, it does not solve it. What is and isn't atomic depends on the use-case, not the types. Same for traversal order. In one case, you may want to flatten a list of lists of tuples completely, in another case those tuples are coordinates and should be preserved. Commented Jun 11, 2020 at 7:52