Converting a list of lists to a single list

Zero Piraeus schesis at
Wed Jul 24 00:49:19 CEST 2013


On 23 July 2013 17:52,  <steve at> wrote:
> Say I have three lists:
> [[A0,A1,A2], [B0,B1,B2] [C0,C1,C2]]
> I would like to convert those to a single list that looks like this:

How's this:

from itertools import chain

def treeify(seq):
    if seq:
        return list(chain(*([x] + treeify(seq[1:]) for x in seq[0])))
        return []

>>> treeify([['A0', 'A1', 'A2'], ['B0', 'B1', 'B2'], ['C0', 'C1', 'C2']])
['A0', 'B0', 'C0', 'C1', 'C2', 'B1', 'C0', 'C1', 'C2', 'B2', 'C0', 'C1', 'C2',
 'A1', 'B0', 'C0', 'C1', 'C2', 'B1', 'C0', 'C1', 'C2', 'B2', 'C0', 'C1', 'C2',
 'A2', 'B0', 'C0', 'C1', 'C2', 'B1', 'C0', 'C1', 'C2', 'B2', 'C0', 'C1', 'C2']


More information about the Python-list mailing list