Timeline for Why doesn't Python have a "flatten" function for lists?
Current License: CC BY-SA 3.0
8 events
| when toggle format | what | by | license | comment | |
|---|---|---|---|---|---|
| Mar 28, 2024 at 23:31 | comment | added | Whatcould | I have rarely seen a clearer illustration of the philosophical/aesthetic difference between Ruby and Python! (Or a confirmation I chose the right language.) Thank you for this answer. | |
| Apr 29, 2022 at 8:28 | comment | added | michael_teter |
Somehow Ruby managed to solve this long ago. It seems the common Python excuse for missing or mis-features is, "who would need that?", or "we couldn't figure out how it should work." The itertools.chain approach cannot handle [1, [3, 4]]. You might want a list like this when collecting items which could be single or lists themselves. It's also handy for ensuring you can call [0] on a value which may or may not be a list.
|
|
| Jun 11, 2020 at 7:52 | comment | added | MisterMiyagi |
@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.
|
|
| Dec 13, 2017 at 22:58 | comment | added | jpmc26 | @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. | |
| Jun 15, 2016 at 22:01 | comment | added | dtc | 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 | |
| Sep 28, 2015 at 11:54 | comment | added | Giorgio |
"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.
|
|
| Apr 16, 2015 at 9:24 | comment | added | Christopher Martin |
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].
|
|
| Aug 28, 2014 at 12:40 | history | answered | Gareth Rees | CC BY-SA 3.0 |