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

Time:02-07

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?

CodePudding user response:

You can unpack the generator:

[*my_gen]
>>[4,5]

CodePudding user response:

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 has the same effect 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

  •  Tags:  
  • Related