To flatten a nested list was (Explanation of this Python language feature? [x for x in x for x in x]

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Mar 28 22:31:36 EDT 2014


On Fri, 28 Mar 2014 17:05:15 -0500, Mark H Harris wrote:

> You might try this to flatten a list of lists:

We got that the first four times you posted it. No need for a fifth. 


>  >>> from functools import reduce
>  >>> L = [[1,2,3],[4,5,6],[7],[8,9]]
>  >>> import operator as λ

Why would you name the operator module the Greek letter l? Why not the 
Armenian letter Ւ (yiwn)? That's pure obfuscation. The operator module has 
nothing to do with "l", and nothing to do with Greek lambda.

This is exactly the sort of foolish obfuscation that opponents warned 
about when Python first introduced support for non-ASCII identifiers.



>  >>> reduce(λ.add, L)
> [1, 2, 3, 4, 5, 6, 7, 8, 9]

Furthermore, this is a very inefficient way of flattening a nested list. 
Doubling the size of the list quadruples the time taken; increasing the 
size by a factor of 10 increases the time by a factor of more than 100:


py> from operator import add
py> from functools import reduce
py> L = [[1]]*10000
py> with Stopwatch():  # code for this available on request
...     x = reduce(add, L)
...
time taken: 0.348851 seconds
py> L = [[1]]*100000
py> with Stopwatch():
...     x = reduce(add, L)
...
time taken: 41.344467 seconds



-- 
Steven D'Aprano
http://import-that.dreamwidth.org/



More information about the Python-list mailing list