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:05:15 CET 2014


On 3/27/14 6:45 PM, Dan Stromberg wrote:
>>
>> x = [[1,2], [3,4], [5,6]]
>>      [x for x in x for x in x]
>
> I'll give this +1 for playfulness, and -2 for lack of clarity.
>
> I hope no one thinks this sort of thing is good to do in real-life code.
>

You might try this to flatten a list of lists:

 >>> 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]

 >>>


marcus



More information about the Python-list mailing list