liv2hak liv2hak - 4 months ago 46
Python Question

Converting generator object to a list

I am trying to wrap my head around

in python. I understand that a function that has an yield returns a generator object. However if I try to convert that generator object to a list it hangs my machine. I am trying to figure out why that is. And what is a more elegant way if any to convert a generator object to a list.

def fib():
a, b = 0, 1
while True:
yield a
a, b = b, a + b

a = fib()

b = fib()



<class 'generator'>
<class 'generator'>


The problem is that your generator has no end condition (while True and no break)

Even if it could make sense to write such a generator (ex: yield all the decimals of Pi or the Fibonacci sequence I just recognized in your code :)), when you convert it to a list, it loops forever (and eats all the memory too)

BTW: list() is of course the best way to turn a (finite :)) generator to a list object.