Is it possible to add the output of a generator when making a list in Python?

Question:

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.

Asked By: Richard Andrew

||

Answers:

Unpack it:

[3, *(0 for i in range(x)), 3]
Answered By: Kelly Bundy
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.