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 :

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

Leave a Reply