Is it possible to make a generator's output be added into a list creation, without making a nested list in Python? I have tried the following code, but it only gives me a generator object, and not the items.
x = 5
expected_list = [3, 0, 0, 0, 0, 0, 3]
list = [3, 0 for i in range(x), 3]
print(list)
I get this error whenever trying to run this code:
list = [3, 0 for i in range(x), 3]
^^^^
SyntaxError: did you forget parentheses around the comprehension target?
If I put parentheses around 0 for i in range(x)
, I get the list
[3, <generator object <genexpr> at 0x000001A065179A10>, 3]
I would like for the generator object to return 0, 0, 0, 0, 0
, without creating a list inside of my list.
CodePudding user response:
Unpack it:
[3, *(0 for i in range(x)), 3]