3 ms·
For flatten, use: flattened = sum(list_of_lists, ())
by numlocked 10y ago
For flatten, use:
flattened = sum(list_of_lists, ())
- darkf 10y agoHuh, that's clever! (You meant `[]` though, yes?)
- mixmastamyk 10y agoIt works, how come no one knows about it??
- ThatGeoGuy 10y agoThis 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.
- brettcannon 10y agoSee https://bugs.python.org/issue27852 https://bugs.python.org/issue27852 for a discussion as to why there isn't a more general flatten().
- 00ajcr 10y agoNo! 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.