How to zip 2 lists but 1 list acts as a single unit?

Question:

I have

a = [5,3,7] 
b = [9,4]

I want

c = [5,3,7,9,5,3,7,4]

Preferably a 1 liner solution that returns the desired output. List has to be flat.

I have tried the following:

[i if j==0 else j for i in [7,4] for j in [5,3,7,0]]

But am wondering if there is an even shorter/cleaner solution.

Asked By: Blo8

||

Answers:

I am not sure whether the following is cleaner, but here’s an option:

a = [5,3,7]
b = [9,4]

output = [x for y in b for x in [*a, y]]
print(output) # [5, 3, 7, 9, 5, 3, 7, 4]

At least it is better than the original code in that it allows for a to have 0 (or any value) as its element.

Answered By: j1-lee
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.