Search code examples
pythonlistpython-itertoolschain

Flattening multiple heterogenous lists in python


There are many posts about flattening lists in python, for example here:

Making a flat list out of list of lists in Python

However, I cannot accomplish the flattening I want using the syntax at those sites, to the best of my knowledge.

my list looks like this:

TargetArray=(line[0:6], AlleleNumber, AltAlleleCount,HQscoreindex,GeneAnnotationFields)

which corresponds to:

(['16', '31363977', '.', 'C', 'T', '.'], 2, 1, '1061,925', ['CGA_FI=3687', 'NM_000887.3', 'ITGAX', 'TSS-UPSTREAM', 'UNKNOWN-INC'])

So the first and last items are themselves lists I would like to expand. I have tried several approaches, including most recently

TargetArray=(line[0:6], AlleleNumber, AltAlleleCount,HQscoreindex,GeneAnnotationFields)
print(TargetArray)
FlatArray=itertools.chain(TargetArray[0])
print(list(FlatArray))

But I cannot seem to get the syntax to work out, perhaps because many of the other examples are more uniform in nature.


Solution

  • Instead of flattening after the fact, just build the list directly by concatenation:

    TargetArray = line[:6] + [AlleleNumber, AltAlleleCount,HQscoreindex] + GeneAnnotationFields