Search code examples
pythonpython-3.xlistlist-comprehensionpython-zip

how to flatten 2D list and add a separator character using zip and list comprehension in python?


I'm trying to write a statement in python that turns this input (for example):

[[3,4],[1],[1,2]]

into this output:

 [3,4,-,1,-,1,2]

using only zip and list comprehension

this is my code:

a = [[1,2],[1],[3,4]]
result = [j for i in zip(a,'-'*len(a)) for j in i]

print(result)

but all I get is:

[[1, 2], '-', [1], '-', [3, 4], '-']

and my output should be this:

[1, 2, '-', 1, '-', 3, 4]

what am I missing?


Solution

  • This should work:

    a = [[1,2],[1],[3,4]]
    result = [a for i in zip(a,'-'*len(a)) for j in i for a in j]
    print(result)
    

    Output:

    [1, 2, '-', 1, '-', 3, 4, '-']
    

    This also works if you don't want the last '-' to be included:

    a = [[1,2],[1],[3,4]]
    result = [a for i in zip(a, '-'*len(a)) for j in i for a in j][:-1]
    print(result)
    

    Output:

    [1, 2, '-', 1, '-', 3, 4]