Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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.

>Solution :

Unpack it:

[3, *(0 for i in range(x)), 3]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading