Let's say i have 2 following functions:
def get_items():
items = []
for i in xrange(2, 10):
items.append(i)
return items
def gen_items():
for i in xrange(2, 10):
yield i
I know i can use both of them in a for loop like this
for item in gen_items():
do something
But now i need to initialize a variable as list, like this
mylist = get_items()
but with the generator function. Is there a way to do it without a for loop appending the items from generator?
mylist = list( get_items() )xrangeis already a generator by the wayxrangereturns an object which is lazy evaluated in Python 2 like therangefunction in Python 3. So if all your generator function is doing is iterate over thexrangeobject, thenlist(xrange(2, 10))will work beautifully.