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

Mark H Harris harrismh777 at gmail.com
Fri Mar 28 23:33:59 EDT 2014


On 3/28/14 9:31 PM, Steven D'Aprano wrote:
> On Fri, 28 Mar 2014 17:05:15 -0500, Mark H Harris wrote:

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

>>   >>> reduce(λ.add, L)
>> [1, 2, 3, 4, 5, 6, 7, 8, 9]
>
> Furthermore, this is a very inefficient way of flattening a nested list.

    Again, its just another way. Its just playful hacking. The serious 
point behind it ( I am able to do anything I want with the language ), I 
mean that is kinda the whole point. For anyone to actually use my little 
hack they need to know that reduce is in functools (right) then they 
need to understand 'reduce' which is a nightmare, and then they need to 
know why chose the symbol  λ  (which was for no other reason than fun. 
Lastly, they would want to flatten a list without

    [x for x in x for x in x]


:)


    The following is a strawman; YOU build it up, to tear it down/

> py> from operator import add
> py> from functools import reduce
> py> L = [[1]]*10000    <===================  my list didn't have ten thousand items

> py> with Stopwatch():  # code for this available on request
> ...     x = reduce(add, L)
> ...
> time taken: 0.348851 seconds
> py> L = [[1]]*100000    <=============  much less one hundred thousand items
> py> with Stopwatch():
> ...     x = reduce(add, L)
> ...
> time taken: 41.344467 seconds     <====  time is an illusion, ask Einstein/


    (Steven, it was all tongue in cheek, just for fun...  )






More information about the Python-list mailing list