How can I use list unpacking with condition in list?

Question:

This is what I’m attempting

[1,2,3 if False else *[6,5,7]]

This is what I’m expecting

[1,2,3,6,5,7]

How could I get this to work without flattening the list – i.e. np.flatten([1,2,3 if False else [6,5,7]]) or similar

Is there an approach I can use to unpack [6,5,7] inside my list? Advice much appreciated!

Asked By: Sam Comber

||

Answers:

You could unpack [6, 5, 7] or an empty list depending on a condition:

condition = False
data = [1, 2, 3, *([] if condition else [6, 5, 7])] 
# >>> [1, 2, 3, 6, 5, 7]
Answered By: Guimoute
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.