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

What are the different ways to convert a generator expression to a list?

mylist = [1,2,3,4,5]
my_gen = (item for item in mylist if item > 3)
new_list = list(my_gen)

passing a generator expression as a list is one way I learned to convert the generator expression into a list. Just curious to know if this can be other in a different way?

>Solution :

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

Unclear if you’re looking for alternatives or just shorter.

For shorter, you don’t need an intermediate variable.

list(item for item in mylist if item > 3)

Which is the same as

[item for item in mylist if item > 3]

For alternatives of the generator, you could use filter function on mylist, but you’d still need list() function, or list-compression, or a while loop calling next() until the generator is exhausted for alternatives of making a list

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