Reputation: 5210
Is there a way to insert multiple elements to a list during a list comprehension in python?
For example:
def a():
return [6,7,8]
[a() if i==2 else i for i in range(4)]
[0, 1, [6, 7, 8], 3]
Would it be possible to get a flat list in one go (function a could return the data in any format).
thanks,
Upvotes: 1
Views: 468
Reputation: 15934
This seems a bit nasty but will work with various datatypes:
import itertools
def a():
return [6,7,8]
l = list(itertools.chain.from_iterable([a() if i==2 else [i] for i in range(4)]))
print(l)
>>>[0, 1, 6, 7, 8, 3]
We can see this also works with other return types from a
:
def a():
return {6,7,8}
>>>[0, 1, 8, 6, 7, 3]
This is already complex enough where I would question going with a one liner approach. It's probably more readable to break this down more.
Upvotes: 1
Reputation: 863
def a(): return [6,7,8]
l = [a() if i==2 else [i] for i in range(4)]
flat = [item for sublist in l for item in sublist]
You could also do it in one go if you combine the last two lines, but that wouldn't be very pythonic.
Upvotes: 1