Re:Problems I Have with Python
by numlocked on Wednesday January 25, 2017 @09:52AM
(#13481800)
For flatten, use:
[ Parent
| on HN ]
Re:Problems I Have with Python
by ThatGeoGuy on Wednesday January 25, 2017 @01:26PM
(#13484260)
This only flattens one level. Consider the following snippets:
; CHICKEN Scheme
#;1> (flatten '((1 2 3) ((4 5) 6) (7 (8) (((((9))))))))
(1 2 3 4 5 6 7 8 9)
#;2> (apply append '((1 2 3) ((4 5) 6) (7 (8) (((((9))))))))
(1 2 3 (4 5) 6 7 (8) (((((9))))))
vs. # Python 3
>>> sum([[1,2,3], [[4,5],6], [7, [8], [[[[[9]]]]]]], [])
[1, 2, 3, [4, 5], 6, 7, [8], [[[[[9]]]]]]
There's a big difference here. Flattening a list to just the elements inside isn't terribly hard, especially in a language like Scheme with tail-recursion, but flatten is definitely something that should be in the standard library. The "flatten" you propose is really just appending the elements of the first level of the list.
Re:Problems I Have with Python
by brettcannon on Wednesday January 25, 2017 @03:35PM
(#13485755)
See https://bugs.python.org/issue27852 for a discussion as to why there isn't a more general flatten().
No! Never do this in Python.
You are making the flattened list by continually concatenating the smaller lists. Each concatenation creates the new bigger list from scratch; the flattened list does not grow dynamically. This is quadratic-performance bad.
Use `list(itertools.chain.from_iterable(...))` instead.
Huh, that's clever! (You meant `[]` though, yes?)
Re:Problems I Have with Python
by mixmastamyk on Wednesday January 25, 2017 @12:50PM
(#13483835)
It works, how come no one knows about it??