mylist = [1, 2, 3, 4, 5]
my_gen = (item for item in mylist if item > 3)
new_list = list(my_gen)
passing the generator expression to the list
function is one way I learned to convert the generator expression into a list. Just curious to know if this can be in any other different way?
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